﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_StockBusiness : BaseBusiness<PB_Stock>, IPB_StockBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly ICheckOperation _check;
        readonly IOperatorDept _odept;
        public PB_StockBusiness(IDbAccessor db, IOperator @operator, ICheckOperation @check, IOperatorDept @odept)
            : base(db)
        {
            _operator = @operator;
            _check = @check;
            _odept = @odept;
        }

        #region 外部接口

        public async Task<PageResult<PB_Stock>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_Stock>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Stock, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_Stock> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_Stock data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_Stock data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        [Transactional]
        public async Task Warehousing(PB_StockDTOquery query)
        {
            await ExecuteSqlAsync("UPDATE PB_PackList SET  Status= '3' WHERE id in (" + string.Format("'{0}'", string.Join(",", query.PackList.ToArray()).Replace(",", "','")) + ")");
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            #region 入库单
            PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
            string dataId = IdHelper.GetId();
            pB_WarehousingNotice.Id = dataId;
            pB_WarehousingNotice.QrCode = "19," + dataId;
            pB_WarehousingNotice.DeptId = bdata.DepartmentId;
            pB_WarehousingNotice.CreatorName = bdata.RealName;
            pB_WarehousingNotice.CreateTime = DateTime.Now;
            pB_WarehousingNotice.CreatorId = _operator.UserId;
            pB_WarehousingNotice.Deleted = false;
            pB_WarehousingNotice.Type = 2;
            await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);
            #endregion
            //用户
            var user = query.UserQRcode?.Split(',')?[1];
            //货位
            var CargoSpace = query.CargoSpaceQRcode?.Split(',')?[1];
            List<PB_Stock> PBStockList = new List<PB_Stock>();
            List<PB_StockLog> PBStockListLog = new List<PB_StockLog>();

            foreach (var item in query.PackList)
            {
                var qdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == item).FirstOrDefaultAsync();
                PB_Stock pB_Stock = new PB_Stock();
                var PrimaryId = IdHelper.GetId();
                pB_Stock.Id = PrimaryId;
                pB_Stock.PackId = item.ToString();
                pB_Stock.LocationId = CargoSpace;
                pB_Stock.StockNumber = qdata.Nums;
                pB_Stock.CreatorId = _operator?.UserId;
                pB_Stock.CreatorName = bdata.RealName;
                pB_Stock.Type = query.Type == null ? 1 : query.Type;
                pB_Stock.OrderID = dataId;
                pB_Stock.CreateTime = DateTime.Now;
                PBStockList.Add(pB_Stock);
                PB_StockLog pB_StockLog = new PB_StockLog();
                pB_StockLog.Id = IdHelper.GetId();
                pB_StockLog.PackId = item.ToString();
                pB_StockLog.LocationId = CargoSpace;
                pB_StockLog.CreatorId = _operator?.UserId;
                pB_StockLog.StockNumber = qdata.Nums;
                pB_StockLog.Deleted = false;
                pB_StockLog.CreatorName = bdata.RealName;
                pB_StockLog.Type = query.Type == null ? 1 : query.Type;
                pB_StockLog.OrderID = dataId;
                pB_StockLog.CreateTime = DateTime.Now;
                pB_StockLog.State = 0;   //状态：0-入库(入库单id)；1-出库(orderId=备货单id)
                PBStockListLog.Add(pB_StockLog);
            }
            await InsertAsync(PBStockList);
            await Db.InsertAsync<PB_StockLog>(PBStockListLog);
        }

        public PageResult<ReturnManagementDTO> WarehousingManagement(ManagementQueryDTO queryDTO)
        {
            PageResult<ReturnManagementDTO> pageResult = new PageResult<ReturnManagementDTO>();
            int PageIndexPage = (queryDTO.PageIndex - 1) * queryDTO.intPageSize;
            int EndPageIndex = queryDTO.intPageSize;
            #region 拼接条件
            string WhereSql = "";
            if (!string.IsNullOrEmpty(queryDTO.Type.ToString()))
            {
                WhereSql += "  and  a.Type=" + queryDTO.Type.ToString() + " ";
            }
            if (!string.IsNullOrEmpty(queryDTO.AssociatedocNo))
            {
                WhereSql += " and d.ID='" + queryDTO.AssociatedocNo + "' ";
            }
            if (!string.IsNullOrEmpty(queryDTO.BeginTime.ToString()))
            {
                WhereSql += "   AND a.CreateTime >='" + queryDTO.BeginTime + "' ";
            }
            if (!string.IsNullOrEmpty(queryDTO.EndTime.ToString()))
            {
                WhereSql += "   AND a.CreateTime <='" + queryDTO.EndTime + "' ";
            }
            #endregion

            #region 
            string sql = @"SELECT  a.Id, 
 CASE a.Type
        WHEN 1 THEN
            '生产产品入库'
        WHEN 2 THEN
            '采购收获入库'
        ELSE
            '退货入库'
    END TypeNameInfo,
        a.CreateTime hosingTime,
        d.POName AssociatedDoc,

      '审核完成' as AuditStatus,
		g.`Name` as supplierInfo,
			ifnull(b.Nums,0) librarySum,
		a.CreatorName Preparer,
        b.CreatorName applicant   FROM PB_Stock a INNER JOIN PB_PackList b on a.PackId = b.Id
LEFT JOIN Base_Department c on b.DeptId = c.ID
LEFT JOIN PB_ProductionOrder d on b.TaskId = d.ID
left join (
select a.PackId,b.OrderDetailId from PB_PackListInfo as a
left join PB_JobBookingQrCode as b on a.JobBookingId=b.Id group by a.PackId,b.OrderDetailId
) as h on a.PackId=h.PackId
LEFT JOIN PB_ProductionOrderDetail e on h.OrderDetailId = e.ParentId
LEFT JOIN PB_Material f on e.MaterialID = f.ID
LEFT JOIN Base_Department g on f.purchaseId = g.Id
WHERE 1 = 1  " + WhereSql + "  ORDER BY a.CreateTime DESC limit " + PageIndexPage + "," + EndPageIndex + "";


            string sqlIn = @"SELECT  a.Id, 
 CASE a.Type
        WHEN 1 THEN
            '生产产品入库'
        WHEN 2 THEN
            '采购收获入库'
        ELSE
            '退货入库'
    END TypeNameInfo,
        a.CreateTime hosingTime,
        d.POName AssociatedDoc,

      '审核完成' as AuditStatus,
		g.`Name` as supplierInfo,
		ifnull(b.Nums,0) librarySum,
		a.CreatorName Preparer,
        b.CreatorName applicant   FROM PB_Stock a INNER JOIN PB_PackList b on a.PackId = b.Id
LEFT JOIN Base_Department c on b.DeptId = c.ID
LEFT JOIN PB_ProductionOrder d on b.TaskId = d.ID
left join (
select a.PackId,b.OrderDetailId from PB_PackListInfo as a
left join PB_JobBookingQrCode as b on a.JobBookingId=b.Id group by a.PackId,b.OrderDetailId
) as h on a.PackId=h.PackId
LEFT JOIN PB_ProductionOrderDetail e on h.OrderDetailId = e.ParentId
LEFT JOIN PB_Material f on e.MaterialID = f.ID
LEFT JOIN Base_Department g on f.purchaseId = g.Id
WHERE 1 = 1   " + WhereSql + "  ORDER BY a.CreateTime DESC";


            #endregion

            var List = Db.GetListBySql<ReturnManagementDTO>(sql);
            var Listin = Db.GetListBySql<ReturnManagementDTO>(sqlIn);

            pageResult.Data = List;
            pageResult.Success = true;
            pageResult.Total = Listin.Count;
            return pageResult;
        }

        public StockDataInfoDTO GetWarehousingManagement(string ReceiptdocNo)
        {

            string sqlIn = @"SELECT a.Id, 
 CASE a.Type
        WHEN 1 THEN
            '生产产品入库'
        WHEN 2 THEN
            '采购收获入库'
        ELSE
            '退货入库'
    END TypeNameInfo,
        a.CreateTime hosingTime,
        d.POName AssociatedDoc,

      '审核完成' as AuditStatus,
		g.`Name` as supplierInfo,
		ifnull(e.CompleteNums,0) librarySum,
		a.CreatorName Preparer,
        b.CreatorName applicant
FROM PB_Stock a INNER JOIN PB_PackList b on a.PackId = b.Id
LEFT JOIN Base_Department c on b.DeptId = c.ID
LEFT JOIN PB_ProductionOrder d on b.TaskId = d.ID
LEFT JOIN PB_ProductionOrderDetail e on d.ID = e.ParentId
LEFT JOIN PB_Material f on e.MaterialID = f.ID
LEFT JOIN Base_Department g on f.purchaseId = g.Id
WHERE 1 = 1   and a.id='" + ReceiptdocNo + "'  ORDER BY a.CreateTime DESC";
            string sql = @"SELECT 
f.`Name` materialName,g.`Name` CargoSpace, ifnull(e.CompleteNums,0) Quantity
FROM PB_Stock a INNER JOIN PB_PackList b on a.PackId = b.Id
LEFT JOIN Base_Department c on b.DeptId = c.Id
LEFT JOIN PB_ProductionOrder d on b.TaskId = d.Id
LEFT JOIN PB_ProductionOrderDetail e on d.ID = e.ParentId
LEFT JOIN PB_Material f on e.MaterialId = f.Id
LEFT JOIN PB_Location g on a.LocationId=g.Id
WHERE 1 = 1  and a.id='" + ReceiptdocNo + "'    ORDER BY a.CreateTime DESC";
            StockDataInfoDTO stockDataInfoDTO = new StockDataInfoDTO();
            stockDataInfoDTO.MainTable = Db.GetListBySql<library>(sqlIn).FirstOrDefault();
            stockDataInfoDTO.SubTable = Db.GetListBySql<Material>(sql);
            return stockDataInfoDTO;

        }

        public async Task<PageResult<InventoryDataDTO>> GetInventoryData(PageInput<QueryGetInventoryDTO> input)
        {

            #region 老的sql
            //            string sql = @"  SELECT   g.Id,g.`Code` MateriaCode,g.AreaId,g.StorId RackId,g.LocationId,d.Id PB_DesignListInfo,c.Id DesignListId,a.Id BatchNumber,d.Nums,d.RealNums ShouldNumber,b.MaterialId,b.EstimatedQuantity,g.MaterialName,g.LocationName,g.StorageName,g.StorAreaName,g.StockNumber  FROM PB_WarehousingNotice a 
            //INNER JOIN PB_ShippingList b on a.Id = b.OddNumber
            //INNER JOIN PB_DesignDetail d on b.SubId = d.Id
            //INNER JOIN PB_DesignList c on d.ParentId = c.Id
            //INNER JOIN(
            //       SELECT a.Id,m.`Code`, c.AreaId, c.StorId, a.LocationId, a.StockNumber, a.MaterialId MaterialId, m.`Name` MaterialName , c.`Name` LocationName, d.`Name` StorageName, e.`Name` StorAreaName FROM PB_Stock a
            //INNER JOIN
            //PB_Material m on a.MaterialId= m.Id
            //LEFT JOIN PB_Location c on a.LocationId = c.id
            //LEFT JOIN (SELECT Id,`Name` FROM Base_Department WHERE Type = 2)  d on c.StorId = d.id
            //LEFT JOIN PB_StorArea e on c.AreaId = e.id
            //) g on b.MaterialId = g.MaterialId  WHERE 1=1   ";
            #endregion
            #region
            //            #region 第二版sql   库存有数据才可以备货 朱柏清注销 2022-03-03
            //            string sql = @" SELECT   g.Id,g.`Code` MateriaCode,g.AreaId,g.StorId RackId,g.LocalId LocationId,d.Id PB_DesignListInfo,c.Id DesignListId,a.Id BatchNumber,d.Nums,d.RealNums ShouldNumber,b.MaterialId,b.EstimatedQuantity,g.MaterialName,g.LocationName,g.StorageName,g.StorAreaName,g.StockNumber  FROM PB_WarehousingNotice a 
            //INNER JOIN PB_ShippingList b on a.Id = b.OddNumber
            //INNER JOIN PB_DesignDetail d on b.SubId = d.Id
            //INNER JOIN PB_DesignList c on d.ParentId = c.Id
            //INNER JOIN(
            //       SELECT a.Id,m.`Code`, c.AreaId, c.StorId, a.LocalId, (a.Nums_N+a.Nums_O-a.Nums_R) StockNumber, a.MaterialId MaterialId, m.`Name` MaterialName , c.`Name` LocationName, d.`Name` StorageName, e.`Name` StorAreaName FROM IT_LocalMaterial a
            //INNER JOIN
            //PB_Material m on a.MaterialId= m.Id
            //LEFT JOIN PB_Location c on a.LocalId = c.id
            //LEFT JOIN (SELECT Id,`Name` FROM Base_Department WHERE Type = 2)  d on c.StorId = d.id
            //LEFT JOIN PB_StorArea e on c.AreaId = e.id
            //) g on b.MaterialId = g.MaterialId  WHERE 1=1          AND g.StockNumber!=0 ";
            //            #endregion


            //            string sql = @"SELECT  *  FROM 
            //(
            //	SELECT  *  FROM  (
            //SELECT
            //	IFNULL(g.StockNumber,0) StockNumber,
            //	d.Id,
            //	m.`Code` MateriaCode,
            //	m.`Spec` MaterialSpec,
            //	g.AreaId,
            //	g.StorId RackId,
            //	g.LocalId LocationId,
            //	d.Id PB_DesignListInfo,
            //	d.Slot Slot,
            //	c.Id DesignListId,
            //	a.Id BatchNumber,
            //	d.RealNums,
            //CASE WHEN IFNULL(d.RealNums,0)-IFNULL(IFNULL(e.StockVolume,0),0)>0 THEN
            //	IFNULL(d.RealNums,0)-IFNULL(IFNULL(e.StockVolume,0),0)
            //      ELSE
            //			0
            //    END  ShouldNumber,
            //IFNULL(e.StockVolume,0) StockVolume,
            //	d.MaterialId,
            //	b.EstimatedQuantity,
            //	m.`Name` MaterialName,
            //	g.LocationName,
            //	g.StorageName,
            //	g.StorAreaName,
            //	g.RackName,
            //	m.Spec,
            //	m.ProductCode
            //FROM
            //	PB_WarehousingNotice a
            //	INNER JOIN PB_ShippingList b ON a.Id = b.OddNumber
            //	LEFT  JOIN PB_DesignDetail d ON b.SubId = d.Id
            //    left join(SELECT SubId,SUM(StockVolume) StockVolume FROM PB_PickUpList GROUP BY SubId) e on d.Id= e.SubId
            //	LEFT JOIN PB_DesignList c ON d.ParentId = c.Id
            //	LEFT JOIN (
            //	SELECT
            //		a.Id,
            //		m.`Code`,
            //		m.`Spec`,
            //		c.AreaId,
            //		c.StorId,
            //		a.LocalId,
            //			IFNULL(( a.Nums_N + a.Nums_O - a.Nums_R ),0) StockNumber,
            //		a.MaterialId MaterialId,
            //		m.`Name` MaterialName,
            //	m.`Spec` MaterialSpec,
            //		c.`Name` LocationName,
            //		d.`Name` StorageName,
            //		e.`Name` StorAreaName ,
            //		rack.`Name` RackName
            //	FROM
            //		IT_LocalMaterial a
            //		INNER JOIN PB_Material m ON a.MaterialId = m.Id
            //		LEFT JOIN PB_Location c ON a.LocalId = c.id
            //		LEFT JOIN ( SELECT Id, `Name` FROM Base_Department WHERE Type = 2 ) d ON c.StorId = d.id
            //		LEFT JOIN PB_StorArea e ON c.AreaId = e.id 
            //			LEFT JOIN PB_Rack rack ON c.RackId = rack.id 
            //	) g ON b.MaterialId = g.MaterialId
            //	LEFT JOIN PB_Material m ON d.MaterialId = m.Id 
            //WHERE 1=1 {0} 
            //order by d.`Slot`
            //) a
            //WHERE 1=1 {1}
            //) a WHERE 1=1 {2}
            // ";
            #endregion
            string sql = @"SELECT
	n.StorAreaName, 
	m.RealNums, 
	n.MateriaCode, 
	n.MaterialName, 
	n.MaterialSpec, 
	n.ProductCode, 
	m.MaterialId, 
	n.StockNumber, 
	t.StockVolume, 
 case	 when IFNULL( m.RealNums, 0 )- IFNULL( t.StockVolume, 0 )<0 then 0 else IFNULL( m.RealNums, 0 )- IFNULL( t.StockVolume, 0 ) end  AS ShouldNumber, 
	n.StorId, 
	PB_DeliveryNoticeItem.Id
FROM
	(
		SELECT
			parentid AS DesignId, 
			MaterialId, 
			SUM(RealNums) as RealNums
		FROM
			PB_DesignDetail
		WHERE
			(
				State = 0 OR
				State = 2
			) AND
			Deleted = 0 GROUP BY parentid,MaterialId
	) AS m
	LEFT JOIN
	(
		SELECT
			StorAreaName, 
			d.`Code` AS MateriaCode, 
			d.`Name` AS MaterialName, 
			d.Spec AS MaterialSpec, 
			b.Nums_N + b.Nums_O - b.Nums_R AS StockNumber, 
			d.ProductCode, 
			b.MaterialId, 
			c.StorId
		FROM
			IT_LocalMaterial AS b
			LEFT JOIN
			View_StorAreaRackLocation AS c
			ON 
				b.LocalId = c.Id
			LEFT JOIN
			PB_Material AS d
			ON 
				b.MaterialId = d.Id
			LEFT JOIN
			Base_UnitItems AS e
			ON 
				d.storageId = e.Id
		WHERE
			b.Deleted = 0
	) AS n
	ON 
		m.MaterialId = n.MaterialId
	LEFT JOIN
	(
		SELECT
			SUM(PB_PickUpList.StockVolume) AS StockVolume, 
			DesignId, 
			MaterialId
		FROM
			PB_PickUpList
			INNER JOIN
			PB_PickUpMain
			ON 
				PB_PickUpList.ParentId = PB_PickUpMain.Id
			LEFT JOIN
			(
				SELECT
					PB_DeliveryNoticeItem.Id, 
					designid
				FROM
					PB_DeliveryNoticeItem
					INNER JOIN
					PB_DeliveryNotice
					ON 
						PB_DeliveryNoticeItem.ParentId = PB_DeliveryNotice.id
			) AS q
			ON 
				PB_PickUpMain.ParentId = q.Id
		WHERE
			PB_PickUpList.Deleted = 0 AND
			PB_PickUpMain.Deleted = 0
		GROUP BY
			DesignId, 
			MaterialId
	) AS t
	ON 
		m.MaterialId = t.MaterialId AND
		m.DesignId = t.DesignId
	INNER JOIN
	PB_DeliveryNoticeItem
	ON 
		m.DesignId = PB_DeliveryNoticeItem.DesignId
WHERE 
	n.StockNumber IS NOT NULL ";
            #region 拼接条件
            //string sqlwhereAreald = "";
            //string sqlMaterialNameCode = "";
            //string sqlwhereStockNumber = "";
            if (!string.IsNullOrEmpty(input.Search.AreaId))
            {
                sql += " AND n.StorId='" + input.Search.AreaId + "' ";
            }
            if (!string.IsNullOrEmpty(input.Search.MaterialNameOrCode))
            {

                sql += " AND   n.`MaterialName` like '%" + input.Search.MaterialNameOrCode + "%'    or     n.`MateriaCode` like '%" + input.Search.MaterialNameOrCode + "%'  ";
            }
            if (!string.IsNullOrEmpty(input.Search.ShippingListId))
            {
                sql += " AND PB_DeliveryNoticeItem.Id='" + input.Search.ShippingListId + "'";
            }
            if (!string.IsNullOrEmpty(input.Search.StockNumber)) {
                if (input.Search.StockNumber == "0")
                {
                    sql += "AND  n.StockNumber=0"; 
                }
                else  if(input.Search.StockNumber=="1"){
                    sql += "AND n.StockNumber>0";
                }
            }
           // sql=  string.Format(sql, sqlwhereAreald, sqlwhereStockNumber, sqlMaterialNameCode);
            #endregion

            var res = await Db.GetListBySqlAsync<InventoryDataDTO>(sql);
            #region   分页处理数据   有bug 没有按照主数据进行处理
            //进行数据分页
            //    public int pagesize = 12;//每一页显示数据的条数，在这里让每一页显示12条
            //public int pageindex;//记录当前的页数为第几页
            int pagecount;//总页数
            List<InventoryDataDTO> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<InventoryDataDTO> productes = new List<InventoryDataDTO>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<InventoryDataDTO> { Data = productes, Total = pagees };
            #endregion
        }

        /// <summary>
        /// 获取要拆包的成品
        /// </summary>
        /// <param name="JobBookingqrcode">成品二维码</param>
        /// <param name="packqrcode">要拆包的二维码</param>
        /// <returns></returns>
        public async Task<PackListDetailDTO> GetJobBookingDataAsync(string JobBookingqrcode, string packqrcode)
        {
            //获取成品id
            string jobbookingId = JobBookingqrcode.Split(',')?[1].ToString();
            //包ID
            string packId = packqrcode.Split(',')?[1].ToString();

            List<IT_LocalDetail> itdata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
            foreach (var item in itdata)
            {
                var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                if (trueorfalse.boolType == false)
                {
                    throw new BusException("仓库物料正在盘点中禁止操作");
                }
            }
            Base_LinkType linktypedata = await Db.GetIQueryable<Base_LinkType>().Where(x => x.LinkType == "MaterialCode").FirstOrDefaultAsync();
            if (linktypedata.Whether == true)
            {
                //获取成品信息
                Expression<Func<PB_JobBookingQrCode, PB_PackListInfo, PB_Material, PackListDetailDTO>> select = (a, b, d) => new PackListDetailDTO
                {
                    Id = b.Id,
                    PackId = a.PackId,
                    JobBookingId = a.Id,
                    CreatorId = b.CreatorId,
                    Deleted = b.Deleted,
                    CreatorName = b.CreatorName,
                    CreatorTime = b.CreatorTime,
                    OldOrNew = b.OldOrNew,
                    MaterialId = a.MaterialId,
                    MaterialCode = d.Code,
                    MaterialSpec = d.Spec,
                    MaterialName = d.Name,
                    IsNumber = d.IsNumber,
                    IsQuantity = d.IsQuantity,
                    SerialNumber = a.SerialNumber
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals b.JobBookingId into ab
                        from b in ab.DefaultIfEmpty()
                        join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                        from d in ad.DefaultIfEmpty()
                        select @select.Invoke(a, b, d);
                PackListDetailDTO data = await q.Where(x => x.JobBookingId == jobbookingId && x.PackId == packId).FirstOrDefaultAsync();
                if (data != null)
                {
                    return data;
                }
                else
                {
                    throw new BusException("成品不在包内");
                }
            }
            else
            {
                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobbookingId && x.PackId == packId).FirstOrDefaultAsync();
                if (jobdata != null)
                {
                    string sqlMain = @"select a.MaterialId,a.PackId,a.OldOrNew,b.`Code` as MaterialCode,b.`Name` as MaterialName,b.Spec as MaterialSpec,Count(a.MaterialId) as Nums from PB_JobBookingQrCode as a left join PB_Material as b on a.MaterialId=b.Id  where a.PackId='" + packId + "' and a.MaterialId='" + jobdata.MaterialId + "' group by a.MaterialId,a.PackId,a.OldOrNew,b.`Code`,b.`Name`,b.Spec";
                    List<PackListDetailDTO> listdata = await Db.GetListBySqlAsync<PackListDetailDTO>(sqlMain);
                    if (listdata.Count > 0)
                    {
                        return listdata.FirstOrDefault();
                    }
                    else
                    {
                        throw new BusException("请检查成品物料是否与包内物料匹配");
                    }
                }
                else
                {
                    throw new BusException("成品不在包内");
                }
            }
        }

        /// <summary>
        /// 拆包获取包的信息
        /// </summary>
        /// <param name="packqrcode">包二维码</param>
        /// <returns></returns>
        public async Task<PB_PackListDTO> GetPackDataAsync(string packqrcode)
        {
            string packId = packqrcode.Split(',')?[1].ToString();
            IT_LocalDetail stockdata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).FirstOrDefaultAsync();
            if (stockdata != null)
            {
                Expression<Func<PB_PackList, PB_Material, PB_PackListDTO>> select = (a, b) => new PB_PackListDTO
                {
                    PackageNum = b.PackageNum
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                PB_PackListDTO packdata = await q.Where(x => x.Id == packId).FirstOrDefaultAsync();
                return packdata;
            }
            else
            {
                throw new BusException("包不存在");
            }
        }


        /// <summary>
        /// 拆包提交信息(全局变量为true)
        /// </summary>
        /// <param name="data"></param>
        /// 2022-03-18   增加库内打包包的入库时间     赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task<PB_PackListDTO> UnpackingDataAsync(UnpackingDataDTO data)
        {
            //获取登录人信息
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //要拆包的包Id
            string packId = data.packqrcode.Split(',')?[1].ToString();

            var deptdata = await _odept.GetOperatorDept();

            PB_PackList PackList = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
            string dataId = IdHelper.GetId();
            if (PackList.PackageType == 0)
            {
                //获取要拆包的包信息
                Expression<Func<PB_PackList, IT_LocalDetail, PB_Material, PB_PackListMaterDTO>> selectPack = (a, b, c) => new PB_PackListMaterDTO
                {
                    StorId = b.StorId,
                    LocalId = b.LocalId,
                    PackageNum = c.PackageNum,
                    IsNumber = c.IsNumber
                };
                selectPack = selectPack.BuildExtendSelectExpre();
                var packq = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                            join b in Db.GetIQueryable<IT_LocalDetail>() on a.Id equals b.PackId into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                            from c in ac.DefaultIfEmpty()
                            select @selectPack.Invoke(a, b, c);
                PB_PackListMaterDTO packdata = await packq.Where(x => x.Id == packId).FirstOrDefaultAsync();

                //生成包信息
                PB_PackList pbdata = new PB_PackList();
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                string dataName = "bag_" + sjtime;
                pbdata.Id = dataId;
                pbdata.DeptId = bdata.DepartmentId;
                pbdata.BoxNo = dataName;
                pbdata.BoxName = packdata.BoxName;
                pbdata.Nums = data.Nums;
                pbdata.TaskId = packdata.TaskId;
                pbdata.MaterialId = packdata.MaterialId;
                pbdata.QrCode = h_Pack + "," + dataId;
                pbdata.Type = 1;
                pbdata.NoticeId = PackList.NoticeId;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreateTime = DateTime.Now;
                pbdata.CreatorName = bdata.RealName;
                pbdata.Status = 3;
                pbdata.State = packdata.State;
                pbdata.OldOrNew = packdata.OldOrNew;
                pbdata.PackageType = 0;
                pbdata.IsUnpacking = true;
                pbdata.InStorTime = DateTime.Now;

                PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                PackMaterialCount.Id = IdHelper.GetId();
                PackMaterialCount.PackId = dataId;
                PackMaterialCount.MaterialId = packdata.MaterialId;
                PackMaterialCount.Nums = data.Nums;

                //拆包日志明细表
                List<PB_UnpackingDetail> listdata = new List<PB_UnpackingDetail>();
                //包明细
                List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();

                //拆包日志主表id
                string unid = IdHelper.GetId();
                PB_Unpacking undata = new PB_Unpacking();
                undata.Id = unid;
                undata.PrimaryPackId = packId;
                undata.NewPackId = dataId;
                undata.Nums = data.Nums;
                undata.OperatorUserId = _operator.UserId;
                undata.OperatorUserName = bdata.RealName;
                undata.CreateTime = DateTime.Now;
                undata.Deleted = false;
                undata.Type = 0;

                string strid = string.Empty;

                //获取要拆包的成品Id,并添加拆包日志、包明细
                foreach (var item in data.jobbookingdata)
                {
                    strid += "'" + item.JobBookingId + "',";
                    PB_UnpackingDetail detdata = new PB_UnpackingDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.ParentId = unid;
                    detdata.JobBookingId = item.JobBookingId;
                    detdata.OldOrNew = item.OldOrNew;
                    detdata.CreatorId = _operator.UserId;
                    detdata.CreatorRealName = bdata.RealName;
                    detdata.CreateTime = DateTime.Now;
                    detdata.Deleted = false;
                    listdata.Add(detdata);

                    PB_PackListInfo infodata = new PB_PackListInfo();
                    infodata.Id = IdHelper.GetId();
                    infodata.PackId = dataId;
                    infodata.JobBookingId = item.JobBookingId;
                    infodata.OldOrNew = item.OldOrNew;
                    infodata.CreatorId = _operator.UserId;
                    infodata.CreatorName = bdata.RealName;
                    infodata.CreatorTime = DateTime.Now;
                    infodata.Deleted = false;
                    listinfo.Add(infodata);
                }

                //库存明细表包减去存库拆包的数量
                string itmaterdetil = @"update IT_LocalDetail set Num=IFNULL(Num,0)-" + data.Nums + " where PackId='" + packId + "'";
                await ExecuteSqlAsync(itmaterdetil);

                //保存库存明细表
                IT_LocalDetail detaildata = new IT_LocalDetail();
                detaildata.Id = IdHelper.GetId();
                detaildata.StorId = packdata.StorId;
                detaildata.LocalId = packdata.LocalId;
                detaildata.MaterialId = packdata.MaterialId;
                detaildata.InTime = DateTime.Now;
                detaildata.CreateTime = DateTime.Now;
                detaildata.CreatorId = _operator.UserId;
                detaildata.Deleted = false;
                detaildata.Num = data.Nums;
                detaildata.PackId = dataId;
                detaildata.OldOrNew = packdata.OldOrNew;
                detaildata.JobId = "";
                await Db.InsertAsync<IT_LocalDetail>(detaildata);

                //原包减去拆出的成品数量
                string sqlpack = @" update PB_PackList set Nums=IFNULL(Nums,0)-" + data.Nums + " where Id='" + packId + "'; ";
                sqlpack += @" update PB_PackMaterialCount  set Nums=IFNULL(Nums,0)-" + data.Nums + " where PackId='" + packId +"' and MaterialId='"+ packdata.MaterialId +"'; ";
                await ExecuteSqlAsync(sqlpack);

                //修改PB_Stock表
                string stocksql = @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + data.Nums + " where PackId='" + packId + "'; ";
                stocksql += @" insert into PB_Stock (Id,PackId,StorId,LocationId,StockNumber,MaterialId,CreatorId,CreatorName,OperatorId,Type,CreateTime,OldOrNew) select " + IdHelper.GetId() + ", " + dataId + ", StorId, LocationId, " + data.Nums + ", MaterialId, '" + _operator.UserId + "', '" + bdata.RealName + "', '" + _operator.UserId + "', Type, now(), OldOrNew from PB_Stock where PackId = '" + packId + "'; ";
                stocksql += @" insert into PB_StockLog (Id,PackId,MaterialId,StorId,LocationId,CreatorId,Deleted,CreatorName,Type,CreateTime,OldOrNew,StockNumber,State) values
('" + IdHelper.GetId() + "','" + dataId + "','" + packdata.MaterialId + "','" + packdata.StorId + "','" + packdata.LocalId + "','" + _operator.UserId + "',0,'" + bdata.RealName + "',1,now(),'" + packdata.OldOrNew + "','" + data.Nums + "',2); ";
                await ExecuteSqlAsync(stocksql);

                strid = strid.Substring(0, strid.Length - 1);
                //删除要拆的包的成品信息
                if (packdata.IsNumber == true)
                {
                    string sqlMain = @" DELETE from PB_PackListInfo where PackId='" + packId + "' and JobBookingId in (" + strid + "); ";
                    sqlMain += @" update PB_JobBookingQrCode set PackId='" + dataId + "' where PackId='" + packId + "' and Id in (" + strid + "); ";
                    await ExecuteSqlAsync(sqlMain);
                }

                if (data.Nums >= PackList.Nums)
                {
                    string sqlMain = @" DELETE from PB_PackList where Id='" + packId + "'; DELETE from PB_PackListInfo where PackId='" + packId + "';   DELETE from IT_LocalDetail where PackId='" + packId + "';";
                    await ExecuteSqlAsync(sqlMain);
                }
                

                //保存拆包日志主表
                await Db.InsertAsync<PB_Unpacking>(undata);

                //保存拆包日志明细表
                await Db.InsertAsync<PB_UnpackingDetail>(listdata);

                //保存新包信息
                await Db.InsertAsync<PB_PackList>(pbdata);

                //保存新包明细信息
                await Db.InsertAsync<PB_PackListInfo>(listinfo);

                //保存新包信息
                await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCount);
            }
            else if (PackList.PackageType == 1)
            {
                //获取要拆包的包信息
                Expression<Func<PB_PackList, IT_LocalDetail, PB_Material, PB_PackListMaterDTO>> selectPack = (a, b, c) => new PB_PackListMaterDTO
                {
                    StorId = b.StorId,
                    LocalId = b.LocalId,
                    Num = b.Num,
                    MaterialId = b.MaterialId,
                    PackageNum = c.PackageNum,
                    IsNumber = c.IsNumber
                };
                selectPack = selectPack.BuildExtendSelectExpre();
                var packq = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                            join b in Db.GetIQueryable<IT_LocalDetail>() on a.Id equals b.PackId into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            select @selectPack.Invoke(a, b, c);
                List<PB_PackListMaterDTO> packdata = await packq.Where(x => x.Id == packId).ToListAsync();

                //查询要查包的成品是多少种物料
                var materdata = data.jobbookingdata.GroupBy(x => new { x.MaterialId, x.MaterialName }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName, Nums = x.Count() }).ToList();

                //生成包信息
                PB_PackList pbdata = new PB_PackList();
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                string dataName = "bag_" + sjtime;
                pbdata.Id = dataId;
                pbdata.DeptId = bdata.DepartmentId;
                pbdata.BoxNo = dataName;
                if (materdata.Count == 1)
                {
                    pbdata.BoxName = materdata.FirstOrDefault().MaterialName;
                    pbdata.PackageType = 0;
                    pbdata.MaterialId = materdata.FirstOrDefault().MaterialId;
                }
                else
                {
                    pbdata.BoxName = materdata.FirstOrDefault().MaterialName + "(混合)";
                    pbdata.PackageType = 1;
                    pbdata.MaterialId = PackList.MaterialId;
                }
                pbdata.NoticeId = PackList.NoticeId;
                pbdata.Nums = data.Nums;
                pbdata.TaskId = PackList.TaskId;
                pbdata.QrCode = h_Pack + "," + dataId;
                pbdata.Type = 1;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreateTime = DateTime.Now;
                pbdata.CreatorName = bdata.RealName;
                pbdata.Status = 3;
                pbdata.State = PackList.State;
                pbdata.OldOrNew = PackList.OldOrNew;
                
                pbdata.IsUnpacking = true;
                pbdata.InStorTime = DateTime.Now;

                //拆包日志明细表
                List<PB_UnpackingDetail> listdata = new List<PB_UnpackingDetail>();
                //包明细
                List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();
                //库存明细
                List<IT_LocalDetail> LocalDetail = new List<IT_LocalDetail>();

                List<PB_PackMaterialCount> PackMaterialCountList = new List<PB_PackMaterialCount>();

                //拆包日志主表id
                string unid = IdHelper.GetId();
                PB_Unpacking undata = new PB_Unpacking();
                undata.Id = unid;
                undata.PrimaryPackId = packId;
                undata.NewPackId = dataId;
                undata.Nums = data.Nums;
                undata.OperatorUserId = _operator.UserId;
                undata.OperatorUserName = bdata.RealName;
                undata.CreateTime = DateTime.Now;
                undata.Deleted = false;
                undata.Type = 0;

                string strid = string.Empty;

                //获取要拆包的成品Id,并添加拆包日志、包明细
                foreach (var item in data.jobbookingdata)
                {
                    strid += "'" + item.JobBookingId + "',";
                    PB_UnpackingDetail detdata = new PB_UnpackingDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.ParentId = unid;
                    detdata.JobBookingId = item.JobBookingId;
                    detdata.OldOrNew = item.OldOrNew;
                    detdata.CreatorId = _operator.UserId;
                    detdata.CreatorRealName = bdata.RealName;
                    detdata.CreateTime = DateTime.Now;
                    detdata.Deleted = false;
                    listdata.Add(detdata);

                    PB_PackListInfo infodata = new PB_PackListInfo();
                    infodata.Id = IdHelper.GetId();
                    infodata.PackId = dataId;
                    infodata.JobBookingId = item.JobBookingId;
                    infodata.OldOrNew = item.OldOrNew;
                    infodata.CreatorId = _operator.UserId;
                    infodata.CreatorName = bdata.RealName;
                    infodata.CreatorTime = DateTime.Now;
                    infodata.Deleted = false;
                    listinfo.Add(infodata);

                    PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                    PackMaterialCount.Id = IdHelper.GetId();
                    PackMaterialCount.PackId = dataId;
                    PackMaterialCount.MaterialId = item.MaterialId;
                    PackMaterialCount.Nums = data.Nums;
                    PackMaterialCountList.Add(PackMaterialCount);
                }

                //库存明细表包减去存库拆包的数量
                string itmaterdetil = string.Empty;
                foreach (var item in materdata)
                {
                    var itemdata = packdata.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    if (itemdata != null)
                    {
                        if (item.Nums == itemdata.Num)
                        {
                            itmaterdetil += @" DELETE from IT_LocalDetail where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                            itmaterdetil += @" DELETE from PB_Stock where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                            itmaterdetil += @" DELETE from PB_PackMaterialCount where Id = '" + packId + "' and MaterialId = '" + item.MaterialId + "'; ";
                        }
                        else
                        {
                            itmaterdetil += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                            itmaterdetil += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                            itmaterdetil += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)-" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        //保存库存明细表
                        IT_LocalDetail detaildata = new IT_LocalDetail();
                        detaildata.Id = IdHelper.GetId();
                        detaildata.StorId = itemdata.StorId;
                        detaildata.LocalId = itemdata.LocalId;
                        detaildata.MaterialId = itemdata.MaterialId;
                        detaildata.InTime = DateTime.Now;
                        detaildata.CreateTime = DateTime.Now;
                        detaildata.CreatorId = _operator.UserId;
                        detaildata.Deleted = false;
                        detaildata.Num = item.Nums;
                        detaildata.PackId = dataId;
                        detaildata.OldOrNew = itemdata.OldOrNew;
                        detaildata.JobId = "";
                        LocalDetail.Add(detaildata);

                        itmaterdetil += @" insert into PB_Stock (Id,PackId,StorId,LocationId,StockNumber,MaterialId,CreatorId,CreatorName,OperatorId,Type,CreateTime,OldOrNew) select " + IdHelper.GetId() + ", " + dataId + ", StorId, LocationId, " + item.Nums + ", MaterialId, '" + _operator.UserId + "', '" + bdata.RealName + "', '" + _operator.UserId + "', Type, now(), OldOrNew from PB_Stock where PackId = '" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                        itmaterdetil += @" insert into PB_StockLog (Id,PackId,MaterialId,StorId,LocationId,CreatorId,Deleted,CreatorName,Type,CreateTime,OldOrNew,StockNumber,State) values
('" + IdHelper.GetId() + "','" + dataId + "','" + item.MaterialId + "','" + packdata.FirstOrDefault().StorId + "','" + packdata.FirstOrDefault().LocalId + "','" + _operator.UserId + "',0,'" + bdata.RealName + "',1,now(),'" + PackList.OldOrNew + "','" + item.Nums + "',2); ";
                    }
                }
                await ExecuteSqlAsync(itmaterdetil);

                //原包减去拆出的成品数量
                string sqlpack = @"update PB_PackList set Nums=IFNULL(Nums,0)-" + data.Nums + " where Id='" + packId + "'";
                await ExecuteSqlAsync(sqlpack);
                strid = strid.Substring(0, strid.Length - 1);
                //删除要拆的包的成品信息
                string sqlMain = " DELETE from PB_PackListInfo where PackId='" + packId + "' and JobBookingId in (" + strid + "); ";
                sqlMain += @" update PB_JobBookingQrCode set PackId='"+ dataId + "' where Id in (" + strid + "); ";
                if (data.Nums >= PackList.Nums)
                {
                    sqlMain += @" DELETE from PB_PackList where Id='" + packId + "'; DELETE from PB_PackListInfo where PackId='" + packId + "';   DELETE from IT_LocalDetail where PackId='" + packId + "';";
                }
                await ExecuteSqlAsync(sqlMain);


                //保存拆包日志主表
                await Db.InsertAsync<PB_Unpacking>(undata);

                //保存拆包日志明细表
                await Db.InsertAsync<PB_UnpackingDetail>(listdata);

                //保存新包信息
                await Db.InsertAsync<PB_PackList>(pbdata);

                //保存库存明细
                await Db.InsertAsync<IT_LocalDetail>(LocalDetail);

                //保存新包明细信息
                await Db.InsertAsync<PB_PackListInfo>(listinfo);

                //保存新包明细信息
                await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCountList);
            }
            //返回包的详细信息
            Expression<Func<PB_PackList, Base_Department, PB_Material, PB_PackListDTO>> select = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = deptdata.DeptName,
                MaterialCode = c.Code,
                MaterialSpec = c.Spec,
                MaterialName = c.Name,
                ProductCode = c.ProductCode
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            q = q.Where(x => x.Id == dataId);
            return await q.FirstOrDefaultAsync();
        }

        /// <summary>
        /// 拆包提交信息(全局变量为false)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task UnpackingPackDataAsync(UnpackingPackDTO data)
        {
            //获取登录人信息
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //要拆包的包Id
            string packId = data.packqrcode.Split(',')?[1].ToString();

            List<PB_UnpackingDetail> UnpackingDetail = new List<PB_UnpackingDetail>();
            //拆包日志主表id
            string unid = IdHelper.GetId();

            PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();

            List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).ToListAsync();

            double? dnums = 0;

            List<string> jobids = new List<string>();

            string sqlMain = string.Empty;

            foreach (var item in data.UnpackingMaterial)
            {
                PB_UnpackingDetail Detail = new PB_UnpackingDetail();
                Detail.Id = IdHelper.GetId();
                Detail.ParentId = unid;
                Detail.JobBookingId = "";
                Detail.OldOrNew = packdata.OldOrNew;
                Detail.CreatorId = _operator.UserId;
                Detail.CreatorRealName = bdata.RealName;
                Detail.CreateTime = DateTime.Now;
                Detail.Deleted = false;
                Detail.PickMainId = "";
                Detail.PickListId = "";
                Detail.MaterialId = item.MaterialId;
                UnpackingDetail.Add(Detail);

                dnums += item.MaterNums;

                int i = 0;
                var itemdata = joblist.Where(x => x.MaterialId == item.MaterialId).ToList();
                foreach (var jobitem in itemdata)
                {
                    i++;
                    if (i <= item.MaterNums)
                    {
                        jobids.Add(jobitem.Id);
                    }
                }
                sqlMain += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)-" + item.MaterNums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";

            }

            sqlMain += @" update PB_JobBookingQrCode set PackStatus=1 where Id in ('" + string.Join("','", jobids.ToArray()) + "'); ";
            sqlMain += @" update PB_PackList set Nums=IFNULL(Nums,0)-" + dnums + " where Id='" + packId + "'; ";

            //拆包主表
            PB_Unpacking undata = new PB_Unpacking();
            undata.Id = unid;
            undata.PrimaryPackId = packId;
            undata.NewPackId = "";
            undata.Nums = dnums;
            undata.OperatorUserId = _operator.UserId;
            undata.OperatorUserName = bdata.RealName;
            undata.CreateTime = DateTime.Now;
            undata.Deleted = false;
            undata.Type = 0;

            List<IT_LocalDetail> LocalDetailList = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();
            List<IT_LocalDetail> LocalDetail = new List<IT_LocalDetail>();

            foreach (var item in LocalDetailList)
            {
                var itemdata = data.UnpackingMaterial.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                if (itemdata != null)
                {
                    //保存库存明细表
                    IT_LocalDetail detaildata = new IT_LocalDetail();
                    detaildata.Id = IdHelper.GetId();
                    detaildata.StorId = item.StorId;
                    detaildata.LocalId = item.LocalId;
                    detaildata.MaterialId = itemdata.MaterialId;
                    detaildata.InTime = DateTime.Now;
                    detaildata.CreateTime = DateTime.Now;
                    detaildata.CreatorId = _operator.UserId;
                    detaildata.Deleted = false;
                    detaildata.Num = itemdata.MaterNums;
                    detaildata.PackId = "";
                    detaildata.OldOrNew = item.OldOrNew;
                    detaildata.JobId = "";
                    detaildata.RecId = "";
                    LocalDetail.Add(detaildata);

                    sqlMain += @" UPDATE IT_LocalDetail SET Num=IFNULL(Num,0)-" + itemdata.MaterNums + " WHERE PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                }
            }

            await Db.InsertAsync<PB_UnpackingDetail>(UnpackingDetail);
            await Db.InsertAsync<PB_Unpacking>(undata);
            await Db.InsertAsync<IT_LocalDetail>(LocalDetail);
            await ExecuteSqlAsync(sqlMain);

        }

        /// <summary>
        /// 扫描合并包
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<PB_PackListDTO> GetNewPackDataAsync(UnpackingDataDTO data)
        {
            PB_PackListDTO PackListDTO = new PB_PackListDTO();
            //合并包的包Id
            string mergepackId = data.mergepackqrcode.Split(',')?[1].ToString();
            //拆出的物料种类
            var jobpackdata = data.jobbookingdata.GroupBy(x => new { x.MaterialId, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, OldOrNew = x.Key.OldOrNew, Nums = x.Count() }).ToList();
            //合并包的信息
            PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == mergepackId).FirstOrDefaultAsync();
            if (jobpackdata.Count == 1)
            {
                if (packdata.PackageType == 0 && jobpackdata.FirstOrDefault().MaterialId != packdata.MaterialId)
                {
                    throw new BusException("拆出的成品与合并的包的物料不匹配！");
                }
                else
                {
                    Expression<Func<PB_PackList, PB_Material, PB_PackListDTO>> select = (a, b) => new PB_PackListDTO
                    {
                        PackageNum = b.PackageNum
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @select.Invoke(a, b);
                    PackListDTO = await q.Where(x => x.Id == mergepackId).FirstOrDefaultAsync();
                }
            }
            else if (jobpackdata.Count > 1)
            {
                if (packdata.PackageType != 1)
                {
                    throw new BusException("合并的包不是混合包不能合并！");
                }
                else
                {
                    Expression<Func<PB_PackList, PB_Material, PB_PackListDTO>> select = (a, b) => new PB_PackListDTO
                    {
                        PackageNum = b.PackageNum
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @select.Invoke(a, b);
                    PackListDTO = await q.Where(x => x.Id == mergepackId).FirstOrDefaultAsync();
                }
            }
            return PackListDTO;
        }

        /// <summary>
        /// 合并提交信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<PB_PackListDTO> MergeUnpackingDataAsync(UnpackingDataDTO data)
        {
            var detpdata = await _odept.GetOperatorDept();

            //获取登录人信息
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //要拆包的包Id
            string packId = data.packqrcode.Split(',')?[1].ToString();
            //合并包的包Id
            string mergepackId = data.mergepackqrcode.Split(',')?[1].ToString();
            //获取拆包的信息
            PB_PackList packlist = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
            //获取合并的包的信息
            PB_PackList mergepacklist= await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == mergepackId).FirstOrDefaultAsync();
            //拆出的物料种类
            var jobpackdata = data.jobbookingdata.GroupBy(x => new { x.MaterialId, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, OldOrNew = x.Key.OldOrNew, Nums = x.Count() }).ToList();

            //拆包日志明细表
            List<PB_UnpackingDetail> listdata = new List<PB_UnpackingDetail>();
            //包明细
            List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();
            //库存明细
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
            List<PB_PackMaterialCount> PackMaterialCountList = new List<PB_PackMaterialCount>();

            List<PB_Stock> stocklist = new List<PB_Stock>();
            //拆包日志主表id
            string unid = IdHelper.GetId();
            PB_Unpacking undata = new PB_Unpacking();
            undata.Id = unid;
            undata.PrimaryPackId = packId;
            undata.NewPackId = mergepackId;
            undata.Nums = data.Nums;
            undata.OperatorUserId = _operator.UserId;
            undata.OperatorUserName = bdata.RealName;
            undata.CreateTime = DateTime.Now;
            undata.Deleted = false;
            undata.Type = 1;

            string strid = string.Empty;
            string itemsql = string.Empty;
            if (jobpackdata.Count == 1)
            {
                IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == jobpackdata.FirstOrDefault().MaterialId && x.PackId == packId).FirstOrDefaultAsync();

                IT_LocalDetail mergeLocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == mergepackId && x.MaterialId == jobpackdata.FirstOrDefault().MaterialId).FirstOrDefaultAsync();

                //获取要拆包的成品Id,并添加拆包日志、包明细
                foreach (var item in data.jobbookingdata)
                {
                    strid += "'" + item.JobBookingId + "',";
                    PB_UnpackingDetail detdata = new PB_UnpackingDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.ParentId = unid;
                    detdata.JobBookingId = item.JobBookingId;
                    detdata.OldOrNew = item.OldOrNew;
                    detdata.CreatorId = _operator.UserId;
                    detdata.CreatorRealName = bdata.RealName;
                    detdata.CreateTime = DateTime.Now;
                    detdata.Deleted = false;
                    listdata.Add(detdata);

                    PB_PackListInfo infodata = new PB_PackListInfo();
                    infodata.Id = IdHelper.GetId();
                    infodata.PackId = mergepackId;
                    infodata.JobBookingId = item.JobBookingId;
                    infodata.OldOrNew = item.OldOrNew;
                    infodata.CreatorId = _operator.UserId;
                    infodata.CreatorName = bdata.RealName;
                    infodata.CreatorTime = DateTime.Now;
                    infodata.Deleted = false;
                    listinfo.Add(infodata);
                }

                //库存明细表包减去存库拆包的数量,合并包增加数量
                if (data.Nums >= packlist.Nums)
                {
                    itemsql += @" delete from IT_LocalDetail where PackId='" + packId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                }
                else
                {
                    itemsql += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + data.Nums + " where PackId='" + packId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                }
                
                //库存汇总表原货位减去要拆出的成品数量,合并包对应的货位增加拆出的成品数量
                string itmaters = string.Empty;
                if (LocalDetail.OldOrNew == 0)
                {
                    itemsql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + data.Nums + " where MaterialId='" + LocalDetail.MaterialId + "' and StorId='" + LocalDetail.StorId + "' and LocalId='" + LocalDetail.LocalId + "'; ";
                }
                else if (LocalDetail.OldOrNew == 1)
                {
                    itemsql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + data.Nums + " where MaterialId='" + LocalDetail.MaterialId + "' and StorId='" + LocalDetail.StorId + "' and LocalId='" + LocalDetail.LocalId + "'; ";
                }
                itemsql += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)-" + data.Nums + " where PackId='" + packId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                //原包减去拆出的成品数量,合并包增加拆出的成品数量
                if (data.Nums >= packlist.Nums)
                {
                    itemsql += @" delete from PB_PackList where Id='" + packId + "'; ";
                }
                else
                {
                    itemsql += @" update PB_PackList set Nums=IFNULL(Nums,0)-" + data.Nums + " where Id='" + packId + "'; ";
                }
                //修改PB_Stock表
                itemsql += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + data.Nums + " where PackId='" + packId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                if (mergeLocalDetail == null)
                {
                    IT_LocalDetail mergedata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == mergepackId).FirstOrDefaultAsync();
                    if (mergedata == null)
                    {
                        throw new BusException("请检查包是否存在");
                    }
                    IT_LocalDetail ldata = new IT_LocalDetail();
                    ldata.Id = IdHelper.GetId();
                    ldata.StorId = mergedata.StorId;
                    ldata.LocalId = mergedata.LocalId;
                    ldata.TrayId = mergedata.TrayId;
                    ldata.MaterialId = jobpackdata.FirstOrDefault().MaterialId;
                    ldata.MeasureId = LocalDetail.MeasureId;
                    ldata.BatchNo = mergedata.BatchNo;
                    ldata.BarCode = mergedata.BarCode;
                    ldata.InTime = DateTime.Now;
                    ldata.Amount = data.Nums * mergedata.Price;
                    ldata.CreateTime = DateTime.Now;
                    ldata.CreatorId = _operator.UserId;
                    ldata.Price = mergedata.Price;
                    ldata.Deleted = false;
                    ldata.Num = data.Nums;
                    ldata.PackId = mergepackId;
                    ldata.OldOrNew = mergedata.OldOrNew;
                    ldata.RecId = mergedata.RecId;
                    ldata.JobId = "";
                    LocalDetailList.Add(ldata);

                    PB_Stock stock = new PB_Stock();
                    stock.Id = IdHelper.GetId();
                    stock.PackId = mergepackId;
                    stock.StorId = mergedata.StorId;
                    stock.LocationId = mergedata.LocalId;
                    stock.StockNumber = data.Nums;
                    stock.MaterialId = jobpackdata.FirstOrDefault().MaterialId;
                    stock.CreatorId = _operator.UserId;
                    stock.CreatorName = bdata.RealName;
                    stock.CreateTime = DateTime.Now;
                    stock.Type = 1;
                    stock.OldOrNew = mergedata.OldOrNew;
                    stock.TS = DateTime.Now;
                    stocklist.Add(stock);
                    if (mergedata.OldOrNew == 0)
                    {
                        itemsql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + jobpackdata.FirstOrDefault().MaterialId + "' and StorId='" + mergedata.StorId + "' and LocalId='" + mergedata.LocalId + "'; ";
                    }
                    else if (mergedata.OldOrNew == 1)
                    {
                        itemsql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where  MaterialId='" + jobpackdata.FirstOrDefault().MaterialId + "' and StorId='" + mergedata.StorId + "' and LocalId='" + mergedata.LocalId + "'; ";
                    }
                }
                else
                {
                    itemsql += @" update IT_LocalDetail set Num=IFNULL(Num,0)+" + data.Nums + " where PackId='" + mergepackId + "' and MaterialId='" + mergeLocalDetail.MaterialId + "'; ";
                    if (mergeLocalDetail.OldOrNew == 0)
                    {
                        itemsql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + mergeLocalDetail.MaterialId + "' and StorId='" + mergeLocalDetail.StorId + "' and LocalId='" + mergeLocalDetail.LocalId + "'; ";
                    }
                    else if (mergeLocalDetail.OldOrNew == 1)
                    {
                        itemsql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + mergeLocalDetail.MaterialId + "' and StorId='" + mergeLocalDetail.StorId + "' and LocalId='" + mergeLocalDetail.LocalId + "'; ";
                    }
                    itemsql += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)+" + data.Nums + " where PackId='" + mergepackId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                }
                itemsql += @" update PB_PackList set Nums=IFNULL(Nums,0)+" + data.Nums + " where Id='" + mergepackId + "'; ";

                strid = strid.Substring(0, strid.Length - 1);
                //删除要拆的包的成品信息
                itemsql += @" DELETE from PB_PackListInfo where PackId='" + packId + "' and JobBookingId in (" + strid + "); ";

                itemsql += @" update PB_JobBookingQrCode set PackId='" + mergepackId + "' where PackId='" + packId + "' and Id in (" + strid + "); ";

                PB_PackMaterialCount PackMaterial = await Db.GetIQueryable<PB_PackMaterialCount>().Where(x => x.PackId == mergepackId).FirstOrDefaultAsync();
                if (PackMaterial != null)
                {
                    itemsql += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)+" + data.Nums + " where PackId='" + mergepackId + "' and MaterialId='"+ mergeLocalDetail.MaterialId + "'; ";
                }
                else
                {
                    PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                    PackMaterialCount.Id = IdHelper.GetId();
                    PackMaterialCount.PackId = mergepackId;
                    PackMaterialCount.MaterialId = mergeLocalDetail.MaterialId;
                    PackMaterialCount.Nums = data.Nums;
                    PackMaterialCountList.Add(PackMaterialCount);
                }
            }
            else if (jobpackdata.Count > 1)
            {
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).ToListAsync();

                List<IT_LocalDetail> mergeLocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == mergepackId).ToListAsync();

                foreach (var item in jobpackdata)
                {
                    var itemLocalDetail = LocalDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    var itemmergeLocalDetail = mergeLocalDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();

                    if (item.Nums >= itemLocalDetail.Num)
                    {
                        itemsql += @" delete from IT_LocalDetail where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                        itemsql += @" delete from PB_PackMaterialCount where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                    }
                    else
                    {
                        itemsql += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                        itemsql += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)-" + data.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";
                    }
                    if (itemLocalDetail.OldOrNew == 0)
                    {
                        itemsql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + itemLocalDetail.StorId + "' and LocalId='" + itemLocalDetail.LocalId + "'; ";
                    }
                    else if (itemLocalDetail.OldOrNew == 1)
                    {
                        itemsql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)-" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + itemLocalDetail.StorId + "' and LocalId='" + itemLocalDetail.LocalId + "'; ";
                    }
                    itemsql += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + item.Nums + " where PackId='" + packId + "' and MaterialId='" + item.MaterialId + "'; ";

                    if (itemmergeLocalDetail == null)
                    {
                        IT_LocalDetail ldata = new IT_LocalDetail();
                        ldata.Id = IdHelper.GetId();
                        ldata.StorId = mergeLocalDetail.FirstOrDefault().StorId;
                        ldata.LocalId = mergeLocalDetail.FirstOrDefault().LocalId;
                        ldata.TrayId = mergeLocalDetail.FirstOrDefault().TrayId;
                        ldata.MaterialId = item.MaterialId;
                        ldata.MeasureId = itemLocalDetail.MeasureId;
                        ldata.BatchNo = mergeLocalDetail.FirstOrDefault().BatchNo;
                        ldata.BarCode = mergeLocalDetail.FirstOrDefault().BarCode;
                        ldata.InTime = DateTime.Now;
                        ldata.Amount = item.Nums * itemLocalDetail.Price;
                        ldata.CreateTime = DateTime.Now;
                        ldata.CreatorId = _operator.UserId;
                        ldata.Price = itemLocalDetail.Price;
                        ldata.Deleted = false;
                        ldata.Num = item.Nums;
                        ldata.PackId = mergepackId;
                        ldata.OldOrNew = mergeLocalDetail.FirstOrDefault().OldOrNew;
                        ldata.RecId = mergeLocalDetail.FirstOrDefault().RecId;
                        ldata.JobId = "";
                        LocalDetailList.Add(ldata);

                        PB_Stock stock = new PB_Stock();
                        stock.Id = IdHelper.GetId();
                        stock.PackId = mergepackId;
                        stock.StorId = mergeLocalDetail.FirstOrDefault().StorId;
                        stock.LocationId = mergeLocalDetail.FirstOrDefault().LocalId;
                        stock.StockNumber = item.Nums;
                        stock.MaterialId = item.MaterialId;
                        stock.CreatorId = _operator.UserId;
                        stock.CreatorName = bdata.RealName;
                        stock.CreateTime = DateTime.Now;
                        stock.Type = 1;
                        stock.OldOrNew = mergeLocalDetail.FirstOrDefault().OldOrNew;
                        stock.TS = DateTime.Now;
                        stocklist.Add(stock);

                        if (mergeLocalDetail.FirstOrDefault().OldOrNew == 0)
                        {
                            itemsql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + mergeLocalDetail.FirstOrDefault().StorId + "' and LocalId='" + mergeLocalDetail.FirstOrDefault().LocalId + "'; ";
                        }
                        else if (mergeLocalDetail.FirstOrDefault().OldOrNew == 1)
                        {
                            itemsql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + mergeLocalDetail.FirstOrDefault().StorId + "' and LocalId='" + mergeLocalDetail.FirstOrDefault().LocalId + "'; ";
                        }
                    }
                    else
                    {
                        itemsql += @" update IT_LocalDetail set Num=IFNULL(Num,0)+" + data.Nums + " where PackId='" + mergepackId + "' and MaterialId='" + item.MaterialId + "'; ";
                        if (mergeLocalDetail.FirstOrDefault().OldOrNew == 0)
                        {
                            itemsql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + mergeLocalDetail.FirstOrDefault().StorId + "' and LocalId='" + mergeLocalDetail.FirstOrDefault().LocalId + "'; ";
                        }
                        else if (mergeLocalDetail.FirstOrDefault().OldOrNew == 1)
                        {
                            itemsql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + mergeLocalDetail.FirstOrDefault().StorId + "' and LocalId='" + mergeLocalDetail.FirstOrDefault().LocalId + "'; ";
                        }
                    }
                    itemsql += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)+" + data.Nums + " where PackId='" + mergepackId + "' and MaterialId='" + item.MaterialId + "'; ";
                    PB_PackMaterialCount PackMaterial = await Db.GetIQueryable<PB_PackMaterialCount>().Where(x => x.PackId == mergepackId && x.MaterialId == item.MaterialId).FirstOrDefaultAsync();
                    if (PackMaterial != null)
                    {
                        itemsql += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)+" + data.Nums + " where PackId='" + mergepackId + "' and MaterialId='" + item.MaterialId + "'; ";
                    }
                    else
                    {
                        PB_PackMaterialCount PackMaterialCount = new PB_PackMaterialCount();
                        PackMaterialCount.Id = IdHelper.GetId();
                        PackMaterialCount.PackId = mergepackId;
                        PackMaterialCount.MaterialId = item.MaterialId;
                        PackMaterialCount.Nums = data.Nums;
                        PackMaterialCountList.Add(PackMaterialCount);
                    }
                }

                //获取要拆包的成品Id,并添加拆包日志、包明细
                foreach (var item in data.jobbookingdata)
                {
                    strid += "'" + item.JobBookingId + "',";
                    PB_UnpackingDetail detdata = new PB_UnpackingDetail();
                    detdata.Id = IdHelper.GetId();
                    detdata.ParentId = unid;
                    detdata.JobBookingId = item.JobBookingId;
                    detdata.OldOrNew = item.OldOrNew;
                    detdata.CreatorId = _operator.UserId;
                    detdata.CreatorRealName = bdata.RealName;
                    detdata.CreateTime = DateTime.Now;
                    detdata.Deleted = false;
                    listdata.Add(detdata);

                    PB_PackListInfo infodata = new PB_PackListInfo();
                    infodata.Id = IdHelper.GetId();
                    infodata.PackId = mergepackId;
                    infodata.JobBookingId = item.JobBookingId;
                    infodata.OldOrNew = item.OldOrNew;
                    infodata.CreatorId = _operator.UserId;
                    infodata.CreatorName = bdata.RealName;
                    infodata.CreatorTime = DateTime.Now;
                    infodata.Deleted = false;
                    listinfo.Add(infodata);
                }
                strid = strid.Substring(0, strid.Length - 1);
                //删除要拆的包的成品信息
                itemsql += @" DELETE from PB_PackListInfo where PackId='" + packId + "' and JobBookingId in (" + strid + "); ";
                itemsql += @" update PB_JobBookingQrCode set PackId='" + mergepackId + "' where PackId='" + packId + "' and Id in (" + strid + "); ";
                if (data.Nums > packlist.Nums)
                {
                    itemsql += @" delete from PB_PackList where Id='" + packId + "'; ";
                }
                else
                {
                    itemsql += @" update PB_PackList set Nums=IFNULL(Nums,0)-" + data.Nums + " where Id='" + packId + "'; ";
                }
                itemsql += @" update PB_PackList set Nums=IFNULL(Nums,0)+" + data.Nums + " where Id='" + mergepackId + "'; ";

            }

            await ExecuteSqlAsync(itemsql);

            //保存拆包日志主表
            await Db.InsertAsync<PB_Unpacking>(undata);

            //保存拆包日志明细表
            await Db.InsertAsync<PB_UnpackingDetail>(listdata);
            //保存新包明细信息
            await Db.InsertAsync<PB_PackListInfo>(listinfo);

            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);

            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCountList);

            await Db.InsertAsync<PB_Stock>(stocklist);
            //返回包的详细信息
            Expression<Func<PB_PackList, Base_Department, PB_Material, PB_PackListDTO>> select = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = detpdata.DeptName,
                MaterialCode = c.Code
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            q = q.Where(x => x.Id == mergepackId);
            return await q.FirstOrDefaultAsync();
        }



        public async Task<PageResult<InventoryDetalDTO>> GetInventorydetalData(PageInput<QueryGetInventoryDTO> input)
        {
            string sql = @" SELECT   g.Id,g.`Code` MateriaCode,g.AreaId,g.StorId RackId,g.LocalId LocationId,d.Id PB_DesignListInfo,c.Id DesignListId,a.Id BatchNumber,d.Nums,d.RealNums ShouldNumber,b.MaterialId,b.EstimatedQuantity,g.MaterialName,g.LocationName,g.StorageName,g.StorAreaName,g.StockNumber,g.Price,(g.StockNumber*g.Price)  zoinghe FROM PB_WarehousingNotice a 
INNER JOIN PB_ShippingList b on a.Id = b.OddNumber
INNER JOIN PB_DesignDetail d on b.SubId = d.Id
INNER JOIN PB_DesignList c on d.ParentId = c.Id
INNER JOIN(
       SELECT m.Price,a.Id,m.`Code`, c.AreaId, c.StorId, a.LocalId, (a.Nums_N+a.Nums_O-a.Nums_R) StockNumber, a.MaterialId MaterialId, m.`Name` MaterialName , c.`Name` LocationName, d.`Name` StorageName, e.`Name` StorAreaName FROM IT_LocalMaterial a
INNER JOIN
PB_Material m on a.MaterialId= m.Id
LEFT JOIN PB_Location c on a.LocalId = c.id
LEFT JOIN (SELECT Id,`Name` FROM Base_Department WHERE Type = 2)  d on c.StorId = d.id
LEFT JOIN PB_StorArea e on c.AreaId = e.id
) g on b.MaterialId = g.MaterialId  WHERE 1=1 ";
            if (!string.IsNullOrEmpty(input.Search.AreaId))
            {
                sql += " AND g.AreaId='" + input.Search.AreaId + "' ";
            }
            if (!string.IsNullOrEmpty(input.Search.MaterialNameOrCode))
            {
                sql += " AND g.`Code` = '" + input.Search.MaterialNameOrCode + "' OR g.MaterialName = '" + input.Search.MaterialNameOrCode + "' ";
            }
            if (!string.IsNullOrEmpty(input.Search.ShippingListId))
            {
                sql += " AND b.ParentId='" + input.Search.ShippingListId + "'";
            }

            var res = await Db.GetListBySqlAsync<InventoryDetalDTO>(sql);
            #region   分页处理数据   有bug 没有按照主数据进行处理
            //进行数据分页
            //    public int pagesize = 12;//每一页显示数据的条数，在这里让每一页显示12条
            //public int pageindex;//记录当前的页数为第几页
            int pagecount;//总页数
            List<InventoryDetalDTO> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<InventoryDetalDTO> productes = new List<InventoryDetalDTO>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<InventoryDetalDTO> { Data = productes, Total = pagees };
            #endregion
        }



        #endregion

        #region  SKU管理合并包

        /// <summary>
        /// 合并包扫描成品物料信息
        /// </summary>
        /// <param name="JobQrCode">成品二维码</param>
        /// <returns></returns>
        public async Task<PackListDetailDTO> GetMergePackListDetailDataAsync(string JobQrCode)
        {
            //成品Id
            string jobid = JobQrCode.Split(',')?[1].ToString();
            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                //获取成品信息
                Expression<Func<PB_JobBookingQrCode, PB_Material, PackListDetailDTO>> select = (a, d) => new PackListDetailDTO
                {
                    Id = a.Id,
                    PackId = a.PackId,
                    JobBookingId = a.Id,
                    MaterialId = a.MaterialId,
                    MaterialCode = d.Code,
                    MaterialSpec = d.Spec,
                    MaterialName = d.Name,
                    IsNumber = d.IsNumber,
                    IsQuantity = d.IsQuantity,
                    SerialNumber = a.SerialNumber
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                PackListDetailDTO data = await q.Where(x => x.JobBookingId == jobid).FirstOrDefaultAsync();
                if (data != null)
                {
                    return data;
                }
                else
                {
                    throw new BusException("成品不在包内");
                }
            }
            else
            {
                throw new BusException("请检查成品编码是否正确");
            }
        }

        /// <summary>
        /// 合并包保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task SaveMergePackListDetailAsync(MergePackListDetail data)
        {
            //合并的包Id
            string packid = data.PackQrCode.Split(',')?[1].ToString();
            //获取当前的成品Id
            List<string> jobids = new List<string>();
            foreach (var item in data.PackListDetail)
            {
                jobids.Add(item.JobBookingId);
            }
            string sqlMain = string.Empty;
            List<PB_PackMaterialCount> PackMaterialCountList = new List<PB_PackMaterialCount>();

            sqlMain += @" update PB_JobBookingQrCode set PackId='" + packid + "',PackStatus=0 where Id in ('" + string.Join("','", jobids.ToArray()) + "'); ";

            sqlMain += @" update PB_PackListInfo set PackId='" + packid + "' where JobBookingId in ('" + string.Join("','", jobids.ToArray()) + "'); ";

            //获取本次合并的物料种类数量
            var materdata = data.PackListDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();

            //获取合并包的物料种类数量
            List<PB_PackMaterialCount> PackMaterialCount = await Db.GetIQueryable<PB_PackMaterialCount>().Where(x => x.PackId == packid).ToListAsync();
            
            //循环查询合并包是否存在
            foreach (var item in materdata)
            {
                var itemdata = PackMaterialCount.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                if (itemdata != null)
                {
                    sqlMain += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)+" + item.Nums + " where PackId='" + packid + "' and MaterialId='" + item.MaterialId + "'; ";
                }
                else
                {
                    PB_PackMaterialCount pmcount = new PB_PackMaterialCount();
                    pmcount.Id = IdHelper.GetId();
                    pmcount.PackId = packid;
                    pmcount.MaterialId = item.MaterialId;
                    pmcount.Nums = item.Nums;
                    PackMaterialCountList.Add(pmcount);
                }
            }
            if (PackMaterialCountList.Count > 0)
            {
                sqlMain += @" update PB_PackList set Nums=IFNULL(Nums,0)+" + data.PackListDetail.Count() + ",PackageType=1 where Id='" + packid + "'; ";
            }
            else
            {
                sqlMain += @" update PB_PackList set Nums=IFNULL(Nums,0)+" + data.PackListDetail.Count() + " where Id='" + packid + "'; ";
            }

            sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)+" + data.PackListDetail.Count() + " where PackId='" + packid + "'; ";

            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCountList);

            await ExecuteSqlAsync(sqlMain);
        }

        #endregion

        #region   移库

        /// <summary>
        /// 获取库里的包信息
        /// </summary>
        /// <param name="packqrcode">包二维码</param>
        /// <param name="LocalQrCode">货位二维码</param>
        /// <returns></returns>
        public async Task<MovePackListDTO> GetStockPackDataAsync(string packqrcode, string LocalQrCode)
        {
            //货位Id
            string localId = LocalQrCode.Split(',')?[1].ToString();
            //包Id
            string packId = packqrcode.Split(',')?[1].ToString();
            if (packId.IsNullOrEmpty())
            {
                throw new BusException("请输入或扫描包二维码");
            }

            string sql = @"select t.Id,t.BoxNo,t.BoxName,t.Nums,t.LocalId,CONCAT(s.`Name`,'/',r.`Name`,'/',l.`Name`) as LocalName,'' as MaterialSepc,'0' as Type from (
select a.PackId as Id,b.BoxNo,b.BoxName,b.Nums,a.LocalId from IT_LocalDetail as a left join PB_PackList as b on a.PackId=b.Id where a.PackId='{0}' and a.LocalId='{1}' and b.PackageType=1 group by a.PackId,b.BoxNo,b.BoxName,b.Nums,a.LocalId 
)as t left join PB_Location as l on t.LocalId=l.Id left join PB_StorArea as s on l.AreaId=s.Id left join PB_Rack as r on l.RackId=r.Id
union ALL
select a.PackId as Id,b.BoxNo,b.BoxName,b.Nums,a.LocalId,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,m.Spec as MaterialSepc,'0' as Type from IT_LocalDetail as a 
left join PB_PackList as b on a.PackId=b.Id
left join PB_Location as c on a.LocalId=c.Id
left join PB_StorArea as d on c.AreaId=d.Id
left join PB_Rack as e on c.RackId=e.Id
left join PB_Material as m on a.MaterialId=m.Id
where a.PackId='{0}' and a.LocalId='{1}' and b.PackageType=0 ";
            string sqlMain = string.Format(sql, packId, localId);
            List<MovePackListDTO> listdata = await Db.GetListBySqlAsync<MovePackListDTO>(sqlMain);
            if (listdata.Count > 0)
            {
                return listdata.FirstOrDefault();
            }
            else
            {
                throw new BusException("请检查当前货位的包是否存在");
            }
        }

        /// <summary>
        /// 获取单个物料信息
        /// </summary>
        /// <param name="MaterialQrCode">物料二维码</param>
        /// <param name="LocalQrCode">货位二维码</param>
        /// <returns></returns>
        public async Task<MovePackListDTO> GetMoveMaterialDataAsync(string MaterialQrCode, string LocalQrCode)
        {
            //货位Id
            string localId = LocalQrCode.Split(',')?[1].ToString();
            //包Id
            string materialId = MaterialQrCode.Split(',')?[1].ToString();
            if (materialId.IsNullOrEmpty())
            {
                throw new BusException("请输入或扫描物料二维码");
            }
            string sql = @"select a.MaterialId as Id,a.MaterialId as BoxNo,b.Name as BoxName,SUM(a.Num) as Nums,a.LocalId,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,b.Spec as MaterialSpec,'1' as Type from IT_LocalDetail as a
left join PB_Material as b on a.MaterialId=b.Id
left join PB_Location as c on a.LocalId=c.Id
left join PB_StorArea as d on c.AreaId=d.Id
left join PB_Rack as e on c.RackId=e.Id
 where a.MaterialId='{0}' and a.LocalId='{1}' and PackId='' and JobId='' 
 group by a.MaterialId,b.Name,b.Spec,a.LocalId ";
            string sqlMain = string.Format(sql, materialId, localId);
            List<MovePackListDTO> listdata = await Db.GetListBySqlAsync<MovePackListDTO>(sqlMain);
            if (listdata.Count > 0)
            {
                return listdata.FirstOrDefault();
            }
            else
            {
                throw new BusException("请检查当前货位的物料是否存在");
            }
        }

        /// <summary>
        /// 获取单个成品物料信息
        /// </summary>
        /// <param name="JobQrCode">成品二维码</param>
        /// <param name="LocalQrCode">货位二维码</param>
        /// <returns></returns>
        public async Task<MovePackListDTO> GetMoveJobDataAsync(string JobQrCode, string LocalQrCode)
        {
            //货位Id
            string localId = LocalQrCode.Split(',')?[1].ToString();
            //包Id
            string jobId = JobQrCode.Split(',')?[1].ToString();
            List<MovePackListDTO> listdata = new List<MovePackListDTO>();

            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobId).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                if (!jobdata.PackId.IsNullOrEmpty())
                {
                    string sql = @"select t.Id,t.BoxNo,t.BoxName,t.Nums,t.LocalId,CONCAT(s.`Name`,'/',r.`Name`,'/',l.`Name`) as LocalName,'' as MaterialSepc,'0' as Type from (
select a.PackId as Id,b.BoxNo,b.BoxName,b.Nums,a.LocalId from IT_LocalDetail as a left join PB_PackList as b on a.PackId=b.Id where a.PackId='{0}' and a.LocalId='{1}' and b.PackageType=1 group by a.PackId,b.BoxNo,b.BoxName,b.Nums,a.LocalId 
)as t left join PB_Location as l on t.LocalId=l.Id left join PB_StorArea as s on l.AreaId=s.Id left join PB_Rack as r on l.RackId=r.Id
union ALL
select a.PackId as Id,b.BoxNo,b.BoxName,b.Nums,a.LocalId,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,m.Spec as MaterialSepc,'0' as Type from IT_LocalDetail as a 
left join PB_PackList as b on a.PackId=b.Id
left join PB_Location as c on a.LocalId=c.Id
left join PB_StorArea as d on c.AreaId=d.Id
left join PB_Rack as e on c.RackId=e.Id
left join PB_Material as m on a.MaterialId=m.Id
where a.PackId='{0}' and a.LocalId='{1}' and b.PackageType=0 ";
                    string sqlMain = string.Format(sql, jobdata.PackId, localId);
                    listdata = await Db.GetListBySqlAsync<MovePackListDTO>(sqlMain);
                }
                else
                {
                    string sql = @"select a.JobId as Id,a.MaterialId as BoxNo,b.Name as BoxName,a.Num as Nums,a.LocalId,CONCAT(d.`Name`,'/',e.`Name`,'/',c.`Name`) as LocalName,b.Spec as MaterialSpec,'2' as Type from IT_LocalDetail as a
left join PB_Material as b on a.MaterialId=b.Id
left join PB_Location as c on a.LocalId=c.Id
left join PB_StorArea as d on c.AreaId=d.Id
left join PB_Rack as e on c.RackId=e.Id
 where a.JobId='{0}' and a.LocalId='{1}' and a.JobId!='' ";
                    string sqlMain = string.Format(sql, jobId, localId);
                    listdata = await Db.GetListBySqlAsync<MovePackListDTO>(sqlMain);
                }
            }
            else
            {
                throw new BusException("请输入或扫描单个成品二维码");
            }
            if (listdata.Count > 0)
            {
                return listdata.FirstOrDefault();
            }
            else
            {
                throw new BusException("请检查当前货位的单个成品物料是否存在");
            }
        }

        /// <summary>
        /// 移库操作
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task TransferLibraryDataAsync(TransferLibraryDTO data)
        {
            //货位Id
            string LocationId = data.Locationqrcode.Split(',')?[1].ToString();
            PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == LocationId).FirstOrDefaultAsync();

            //获取操作人信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //获取货位信息
            List<PB_Location> Location = await Db.GetIQueryable<PB_Location>().ToListAsync();

            //获取库存汇总数据
            List<IT_LocalMaterial> listdata = await Db.GetIQueryable<IT_LocalMaterial>().ToListAsync();

            List<TD_MoveDetail> MoveDetaillist = new List<TD_MoveDetail>();
            List<IT_RecordBook> iT_RecordBooks = new List<IT_RecordBook>();
            List<PB_StockLog> StockLog = new List<PB_StockLog>();
            List<IT_LocalMaterial> LocalMaterial = new List<IT_LocalMaterial>();
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
           
            string sqlMain = string.Empty;

            string moveId = IdHelper.GetId();

            //获取包的数据
            var packlist = data.MovePackList.Where(x => x.Type == 0).ToList();
            if (packlist.Count > 0)
            {
                List<string> PackIds = new List<string>();
                foreach (var item in packlist)
                {
                    PackIds.Add(item.Id);
                }
                //获取包在仓库的明细信息
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => PackIds.Contains(x.PackId)).ToListAsync();
                foreach (var item in LocalDetail)
                {
                    var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止操作");
                    }
                    if (locadata.StorId != item.StorId)
                    {
                        throw new BusException("不同仓库不能移库操作,请做调拨处理");
                    }
                    //查询物料在要移库的货位是否有数据
                    var itemMaterial = listdata.Where(x => x.MaterialId == item.MaterialId && x.LocalId == LocationId).FirstOrDefault();
                    //减去原货位的库存
                    if (item.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "'; ";
                    }
                    else if (item.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "'; ";
                    }
                    var itemLocalMaterial = LocalMaterial.Where(x => x.MaterialId == item.MaterialId && x.LocalId == LocationId).FirstOrDefault();
                    //新货位查询不到物料信息时添加新的库存汇总信息
                    if (itemMaterial == null && itemLocalMaterial == null)
                    {
                        if (item.OldOrNew == 0)
                        {
                            IT_LocalMaterial addMater = new IT_LocalMaterial();
                            addMater.Id = IdHelper.GetId();
                            addMater.MaterialId = item.MaterialId;
                            addMater.StorId = locadata.StorId;
                            addMater.LocalId = LocationId;
                            addMater.Nums_O = Convert.ToDouble(item.Num);
                            addMater.Nums_N = 0;
                            addMater.Nums_R = 0;
                            addMater.ScanNum = Convert.ToDouble(item.Num);
                            addMater.CreatorId = _operator.UserId;
                            addMater.CreateTime = DateTime.Now;
                            addMater.Deleted = false;
                            addMater.AreaId = locadata.AreaId;
                            addMater.RackId = locadata.RackId;
                            addMater.ScanNum = 0;
                            LocalMaterial.Add(addMater);
                        }
                        else if (item.OldOrNew == 1)
                        {
                            IT_LocalMaterial addMater = new IT_LocalMaterial();
                            addMater.Id = IdHelper.GetId();
                            addMater.MaterialId = item.MaterialId;
                            addMater.StorId = locadata.StorId;
                            addMater.LocalId = LocationId;
                            addMater.Nums_O = 0;
                            addMater.Nums_N = Convert.ToDouble(item.Num);
                            addMater.Nums_R = 0;
                            addMater.ScanNum = Convert.ToDouble(item.Num);
                            addMater.CreatorId = _operator.UserId;
                            addMater.CreateTime = DateTime.Now;
                            addMater.Deleted = false;
                            addMater.AreaId = locadata.AreaId;
                            addMater.RackId = locadata.RackId;
                            addMater.ScanNum = 0;
                            LocalMaterial.Add(addMater);
                        }
                    }
                    else  //新货位查询到物料信息时修改库存汇总信息
                    {
                        if (item.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Num + ",ScanNum=IFNULL(ScanNum,0)+" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + LocationId + "'; ";
                        }
                        else if (item.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Num + ",ScanNum=IFNULL(ScanNum,0)+" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + LocationId + "'; ";
                        }
                    }
                    //添加移库明细
                    TD_MoveDetail mdata = new TD_MoveDetail();
                    mdata.Id = IdHelper.GetId();
                    mdata.MoveId = moveId;
                    mdata.StorId = item.StorId;
                    mdata.FromLocalId = item.LocalId;
                    mdata.ToLocalId = LocationId;
                    mdata.MaterialId = item.MaterialId;
                    mdata.Price = Convert.ToDouble(item.Price);
                    mdata.LocalNum = 0;
                    mdata.MoveNum = Convert.ToDouble(item.Num);
                    mdata.Amount = Convert.ToDouble(item.Amount);
                    mdata.CreateTime = DateTime.Now;
                    mdata.CreatorId = _operator.UserId;
                    mdata.Deleted = false;
                    mdata.PackId = item.PackId;
                    mdata.JobId = "";
                    MoveDetaillist.Add(mdata);
                    //添加台账数据
                    IT_RecordBook iT_RecordBook = new IT_RecordBook();
                    iT_RecordBook.Id = IdHelper.GetId();
                    iT_RecordBook.RefCode = moveId;
                    iT_RecordBook.Type = "MoveIn";
                    var Storid = await Db.GetIQueryable<PB_Location>().Where(m => m.Id == item.LocalId).FirstOrDefaultAsync();
                    iT_RecordBook.FromStorId = Storid.StorId;
                    iT_RecordBook.FromLocalId = item.LocalId;
                    var StoridS = await Db.GetIQueryable<PB_Location>().Where(m => m.Id == LocationId).FirstOrDefaultAsync();
                    iT_RecordBook.ToStorId = StoridS.StorId;
                    iT_RecordBook.ToLocalId = LocationId;
                    iT_RecordBook.MaterialId = item.MaterialId;
                    iT_RecordBook.MeasureId = "";
                    iT_RecordBook.BarCode = "";
                    iT_RecordBook.BatchNo = "";
                    iT_RecordBook.Num = Convert.ToDouble(item.Num);
                    iT_RecordBook.CreateTime = DateTime.Now;
                    iT_RecordBook.CreatorId = _operator.UserId;
                    iT_RecordBook.Deleted = false;
                    iT_RecordBooks.Add(iT_RecordBook);
                    //库存日志增加移库
                    PB_StockLog logdata = new PB_StockLog();
                    logdata.Id = IdHelper.GetId();
                    logdata.PackId = item.PackId;
                    logdata.MaterialId = item.MaterialId;
                    logdata.StorId = locadata.StorId;
                    logdata.LocationId = LocationId;
                    logdata.StockNumber = item.Num;
                    logdata.CreatorId = _operator.UserId;
                    logdata.CreatorName = userdata.RealName;
                    logdata.CreateTime = DateTime.Now;
                    logdata.OperatorId = _operator.UserId;
                    logdata.Type = 1;
                    logdata.Deleted = false;
                    logdata.State = 2;
                    logdata.OldOrNew = item.OldOrNew;
                    logdata.JobId = "";
                    StockLog.Add(logdata);

                    
                    sqlMain += @" update PB_Stock set LocationId='" + LocationId + "' where PackId='" + item.PackId + "'; ";
                    sqlMain += @" update IT_LocalDetail set LocalId='" + LocationId + "',StorId='" + locadata.StorId + "' where PackId='" + item.PackId + "'; ";

                }
            }

            //获取单个物料的数据(单个物料默认为新)
            var materialdata = data.MovePackList.Where(x => x.Type == 1).ToList();
            if (materialdata.Count > 0)
            {
                List<string> materialIds = new List<string>();
                //获取物料信息
                var locamaterial = materialdata.GroupBy(x => new { x.Id, x.LocalId }).Select(x => new { Id = x.Key.Id, LocalId = x.Key.LocalId }).ToList();
                foreach (var item in locamaterial)
                {
                    materialIds.Add(item.Id);
                }
                //获取仓库的物料明细信息
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => materialIds.Contains(x.MaterialId) && x.PackId == "").ToListAsync();
                List<PB_Stock> PB_Stocklist = await Db.GetIQueryable<PB_Stock>().Where(x => materialIds.Contains(x.MaterialId) && x.PackId == "").ToListAsync();

                foreach (var item in materialdata)
                {
                    //移库的物料数量
                    double? itemnums = item.Nums;
                    //获取物料在货位的所有数据
                    var itemLocalDetail = LocalDetail.Where(x => x.MaterialId == item.Id && x.LocalId == item.LocalId).ToList();
                    foreach (var itemdata in itemLocalDetail)
                    {
                        if (locadata.StorId != itemdata.StorId)
                        {
                            throw new BusException("不同仓库不能移库操作,请做调拨处理");
                        }
                        if (itemnums > 0)
                        {
                            if (itemdata.Num == itemnums)
                            {
                                itemnums -= itemdata.Num;
                                if (itemdata.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itemdata.Num + ",ScanNum=IFNULL(ScanNum,0)-" + itemdata.Num + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                }
                                else if (itemdata.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itemdata.Num + ",ScanNum=IFNULL(ScanNum,0)-" + itemdata.Num + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                }
                                sqlMain += @" delete from IT_LocalDetail where Id='" + itemdata.Id + "'; ";
                            }
                            else if (itemdata.Num < itemnums)
                            {
                                if (itemnums >= itemdata.Num)
                                {
                                    itemnums -= itemdata.Num;
                                    if (itemdata.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itemdata.Num + ",ScanNum=IFNULL(ScanNum,0)-" + itemdata.Num + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                    }
                                    else if (itemdata.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itemdata.Num + ",ScanNum=IFNULL(ScanNum,0)-" + itemdata.Num + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                    }
                                    sqlMain += @" delete from IT_LocalDetail where Id='" + itemdata.Id + "'; ";
                                }
                                else
                                {
                                    if (itemdata.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                    }
                                    else if (itemdata.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                    }
                                    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + itemnums + " where Id='" + itemdata.Id + "'; ";
                                    itemnums -= itemnums;
                                }
                            }
                            else if (itemdata.Num > itemnums)
                            {
                                itemdata.Num -= itemnums;
                                if (itemdata.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                }
                                else if (itemdata.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + itemnums + ",ScanNum=IFNULL(ScanNum,0)-" + itemnums + " where StorId='" + itemdata.StorId + "' and LocalId='" + itemdata.LocalId + "' and MaterialId='" + itemdata.MaterialId + "'; ";
                                }
                                sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + itemnums + " where Id='" + itemdata.Id + "'; ";
                                itemnums -= itemnums;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    //PB_Stock
                    itemnums = item.Nums;
                    var stocklist = PB_Stocklist.Where(x => x.MaterialId == item.Id && x.LocationId == item.LocalId).ToList();
                    foreach (var itemdata in stocklist)
                    {
                        if (itemnums != 0)
                        {
                            //出库数量等于库存明细数量时
                            if (itemdata.StockNumber == itemnums)
                            {
                                itemnums -= itemdata.StockNumber;
                                sqlMain += @" delete from PB_Stock where Id='" + itemdata.Id + "'; ";
                            }
                            else if (itemdata.StockNumber < itemnums)   //出库数量大于库存明细数量时
                            {
                                if (itemnums >= itemdata.StockNumber)
                                {
                                    itemnums -= itemdata.StockNumber;
                                    sqlMain += @" delete from PB_Stock where Id='" + itemdata.Id + "'; ";
                                }
                                else
                                {
                                    sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + itemnums + " where Id='" + item.Id + "'; ";
                                    itemnums -= itemnums;
                                }
                            }
                            else if (itemdata.StockNumber > itemnums) //出库数量小于库存明细数量时
                            {
                                itemdata.StockNumber -= itemnums;
                                sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + itemnums + " where Id='" + item.Id + "'; ";
                                itemnums -= itemnums;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    //查询物料在要移库的货位是否有数据
                    var itemMaterial = listdata.Where(x => x.MaterialId == item.Id && x.LocalId == LocationId).FirstOrDefault();

                    //查询本次添加的库存汇总时候有值
                    var itemLocalMaterial = LocalMaterial.Where(x => x.MaterialId == item.Id && x.LocalId == LocationId).FirstOrDefault();
                    //新货位查询不到物料信息时添加新的库存汇总信息
                    if (itemMaterial == null && itemLocalMaterial == null)
                    {
                        IT_LocalMaterial addMater = new IT_LocalMaterial();
                        addMater.Id = IdHelper.GetId();
                        addMater.MaterialId = item.Id;
                        addMater.StorId = locadata.StorId;
                        addMater.LocalId = LocationId;
                        addMater.Nums_O = 0;
                        addMater.Nums_N = Convert.ToDouble(item.Nums);
                        addMater.Nums_R = 0;
                        addMater.ScanNum = Convert.ToDouble(item.Nums);
                        addMater.CreatorId = _operator.UserId;
                        addMater.CreateTime = DateTime.Now;
                        addMater.Deleted = false;
                        addMater.AreaId = locadata.AreaId;
                        addMater.RackId = locadata.RackId;
                        addMater.ScanNum = 0;
                        LocalMaterial.Add(addMater);
                    }
                    else
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + "  where MaterialId='" + item.Id + "' and StorId='" + locadata.StorId + "' and LocalId='" + LocationId + "'; ";
                    }

                    var detaildata = LocalDetail.FirstOrDefault();
                    //库存明细
                    IT_LocalDetail Detail = new IT_LocalDetail();
                    Detail.Id = IdHelper.GetId();
                    Detail.StorId = locadata.StorId;
                    Detail.LocalId = LocationId;
                    Detail.MaterialId = item.Id;
                    Detail.BarCode = h_Material + "," + item.Id;
                    Detail.InTime = DateTime.Now;
                    Detail.Amount = detaildata.Price * item.Nums;
                    Detail.CreateTime = DateTime.Now;
                    Detail.CreatorId = _operator.UserId;
                    Detail.Price = detaildata.Price;
                    Detail.Deleted = false;
                    Detail.Num = item.Nums;
                    Detail.PackId = "";
                    Detail.OldOrNew = 1;
                    Detail.RecId = "";
                    Detail.JobId = "";
                    LocalDetailList.Add(Detail);

                    var madata = itemLocalDetail.GroupBy(x => new { x.StorId, x.Price, x.OldOrNew }).Select(x => new { StorId = x.Key.StorId, Price = x.Key.Price, OldOrNew = x.Key.OldOrNew }).FirstOrDefault();
                    //添加移库明细
                    TD_MoveDetail mdata = new TD_MoveDetail();
                    mdata.Id = IdHelper.GetId();
                    mdata.MoveId = moveId;
                    mdata.StorId = madata.StorId;
                    mdata.FromLocalId = item.LocalId;
                    mdata.ToLocalId = LocationId;
                    mdata.MaterialId = item.Id;
                    mdata.Price = Convert.ToDouble(madata.Price);
                    mdata.LocalNum = 0;
                    mdata.MoveNum = Convert.ToDouble(item.Nums);
                    mdata.Amount = Convert.ToDouble(item.Nums * madata.Price);
                    mdata.CreateTime = DateTime.Now;
                    mdata.CreatorId = _operator.UserId;
                    mdata.Deleted = false;
                    mdata.PackId = "";
                    mdata.JobId = "";
                    MoveDetaillist.Add(mdata);
                    //添加台账数据
                    IT_RecordBook iT_RecordBook = new IT_RecordBook();
                    iT_RecordBook.Id = IdHelper.GetId();
                    iT_RecordBook.RefCode = moveId;
                    iT_RecordBook.Type = "MoveIn";
                    var Storid = await Db.GetIQueryable<PB_Location>().Where(m => m.Id == item.LocalId).FirstOrDefaultAsync();
                    iT_RecordBook.FromStorId = Storid.StorId;
                    iT_RecordBook.FromLocalId = item.LocalId;
                    var StoridS = await Db.GetIQueryable<PB_Location>().Where(m => m.Id == LocationId).FirstOrDefaultAsync();
                    iT_RecordBook.ToStorId = StoridS.StorId;
                    iT_RecordBook.ToLocalId = LocationId;
                    iT_RecordBook.MaterialId = item.Id;
                    iT_RecordBook.MeasureId = "";
                    iT_RecordBook.BarCode = "";
                    iT_RecordBook.BatchNo = "";
                    iT_RecordBook.Num = Convert.ToDouble(item.Nums);
                    iT_RecordBook.CreateTime = DateTime.Now;
                    iT_RecordBook.CreatorId = _operator.UserId;
                    iT_RecordBook.Deleted = false;
                    iT_RecordBooks.Add(iT_RecordBook);
                    //库存日志增加移库
                    PB_StockLog logdata = new PB_StockLog();
                    logdata.Id = IdHelper.GetId();
                    logdata.PackId = "";
                    logdata.MaterialId = item.Id;
                    logdata.StorId = locadata.StorId;
                    logdata.LocationId = LocationId;
                    logdata.StockNumber = item.Nums;
                    logdata.CreatorId = _operator.UserId;
                    logdata.CreatorName = userdata.RealName;
                    logdata.CreateTime = DateTime.Now;
                    logdata.OperatorId = _operator.UserId;
                    logdata.Type = 1;
                    logdata.Deleted = false;
                    logdata.State = 2;
                    logdata.OldOrNew = madata.OldOrNew;
                    logdata.JobId = "";
                    StockLog.Add(logdata);

                    

                }

            }
            //获取单个成品的数据
            var jobdata = data.MovePackList.Where(x => x.Type == 2).ToList();
            if (jobdata.Count > 0)
            {
                List<string> jobIds = new List<string>();
                foreach (var item in jobdata)
                {
                    jobIds.Add(item.Id);
                }
                //获取包在仓库的明细信息
                List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => jobIds.Contains(x.JobId)).ToListAsync();
                foreach (var item in LocalDetail)
                {
                    if (locadata.StorId != item.StorId)
                    {
                        throw new BusException("不同仓库不能移库操作,请做调拨处理");
                    }
                    var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止操作");
                    }
                    //查询物料在要移库的货位是否有数据
                    var itemMaterial = listdata.Where(x => x.MaterialId == item.MaterialId && x.LocalId == LocationId).FirstOrDefault();
                    //减去原货位的库存
                    if (item.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "'; ";
                    }
                    else if (item.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "'; ";
                    }
                    var itemLocalMaterial = LocalMaterial.Where(x => x.MaterialId == item.MaterialId && x.LocalId == LocationId).FirstOrDefault();
                    //新货位查询不到物料信息时添加新的库存汇总信息
                    if (itemMaterial == null && itemLocalMaterial == null)
                    {
                        if (item.OldOrNew == 0)
                        {
                            IT_LocalMaterial addMater = new IT_LocalMaterial();
                            addMater.Id = IdHelper.GetId();
                            addMater.MaterialId = item.MaterialId;
                            addMater.StorId = locadata.StorId;
                            addMater.LocalId = LocationId;
                            addMater.Nums_O = Convert.ToDouble(item.Num);
                            addMater.Nums_N = 0;
                            addMater.Nums_R = 0;
                            addMater.ScanNum = Convert.ToDouble(item.Num);
                            addMater.CreatorId = _operator.UserId;
                            addMater.CreateTime = DateTime.Now;
                            addMater.Deleted = false;
                            addMater.AreaId = locadata.AreaId;
                            addMater.RackId = locadata.RackId;
                            addMater.ScanNum = 0;
                            LocalMaterial.Add(addMater);
                        }
                        else if (item.OldOrNew == 1)
                        {
                            IT_LocalMaterial addMater = new IT_LocalMaterial();
                            addMater.Id = IdHelper.GetId();
                            addMater.MaterialId = item.MaterialId;
                            addMater.StorId = locadata.StorId;
                            addMater.LocalId = LocationId;
                            addMater.Nums_O = 0;
                            addMater.Nums_N = Convert.ToDouble(item.Num);
                            addMater.Nums_R = 0;
                            addMater.ScanNum = Convert.ToDouble(item.Num);
                            addMater.CreatorId = _operator.UserId;
                            addMater.CreateTime = DateTime.Now;
                            addMater.Deleted = false;
                            addMater.AreaId = locadata.AreaId;
                            addMater.RackId = locadata.RackId;
                            addMater.ScanNum = 0;
                            LocalMaterial.Add(addMater);
                        }
                    }
                    else  //新货位查询到物料信息时修改库存汇总信息
                    {
                        if (item.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Num + ",ScanNum=IFNULL(ScanNum,0)+" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + LocationId + "'; ";
                        }
                        else if (item.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Num + ",ScanNum=IFNULL(ScanNum,0)+" + item.Num + "  where MaterialId='" + item.MaterialId + "' and StorId='" + locadata.StorId + "' and LocalId='" + LocationId + "'; ";
                        }
                    }
                    //添加移库明细
                    TD_MoveDetail mdata = new TD_MoveDetail();
                    mdata.Id = IdHelper.GetId();
                    mdata.MoveId = moveId;
                    mdata.StorId = item.StorId;
                    mdata.FromLocalId = item.LocalId;
                    mdata.ToLocalId = LocationId;
                    mdata.MaterialId = item.MaterialId;
                    mdata.Price = Convert.ToDouble(item.Price);
                    mdata.LocalNum = 0;
                    mdata.MoveNum = Convert.ToDouble(item.Num);
                    mdata.Amount = Convert.ToDouble(item.Amount);
                    mdata.CreateTime = DateTime.Now;
                    mdata.CreatorId = _operator.UserId;
                    mdata.Deleted = false;
                    mdata.PackId = item.PackId;
                    mdata.JobId = "";
                    MoveDetaillist.Add(mdata);
                    //添加台账数据
                    IT_RecordBook iT_RecordBook = new IT_RecordBook();
                    iT_RecordBook.Id = IdHelper.GetId();
                    iT_RecordBook.RefCode = moveId;
                    iT_RecordBook.Type = "MoveIn";
                    var Storid = await Db.GetIQueryable<PB_Location>().Where(m => m.Id == item.LocalId).FirstOrDefaultAsync();
                    iT_RecordBook.FromStorId = Storid.StorId;
                    iT_RecordBook.FromLocalId = item.LocalId;
                    var StoridS = await Db.GetIQueryable<PB_Location>().Where(m => m.Id == LocationId).FirstOrDefaultAsync();
                    iT_RecordBook.ToStorId = StoridS.StorId;
                    iT_RecordBook.ToLocalId = LocationId;
                    iT_RecordBook.MaterialId = item.Id;
                    iT_RecordBook.MeasureId = "";
                    iT_RecordBook.BarCode = "";
                    iT_RecordBook.BatchNo = "";
                    iT_RecordBook.Num = Convert.ToDouble(item.Num);
                    iT_RecordBook.CreateTime = DateTime.Now;
                    iT_RecordBook.CreatorId = _operator.UserId;
                    iT_RecordBook.Deleted = false;
                    iT_RecordBooks.Add(iT_RecordBook);
                    //库存日志增加移库
                    PB_StockLog logdata = new PB_StockLog();
                    logdata.Id = IdHelper.GetId();
                    logdata.PackId = item.PackId;
                    logdata.MaterialId = item.MaterialId;
                    logdata.StorId = locadata.StorId;
                    logdata.LocationId = LocationId;
                    logdata.StockNumber = item.Num;
                    logdata.CreatorId = _operator.UserId;
                    logdata.CreatorName = userdata.RealName;
                    logdata.CreateTime = DateTime.Now;
                    logdata.OperatorId = _operator.UserId;
                    logdata.Type = 1;
                    logdata.Deleted = false;
                    logdata.State = 2;
                    logdata.OldOrNew = item.OldOrNew;
                    logdata.JobId = "";
                    StockLog.Add(logdata);


                    

                    sqlMain += @" update PB_Stock set LocationId='" + LocationId + "' where JobId='" + item.JobId + "'; ";
                    sqlMain += @" update IT_LocalDetail set LocalId='" + LocationId + "',StorId='" + locadata.StorId + "' where JobId='" + item.JobId + "'; ";
                }
            }

            double? dnum = 0;
            foreach (var item in MoveDetaillist)
            {
                dnum += item.MoveNum;
            }

            //移库主表信息
            TD_Move movedata = new TD_Move();
            movedata.Id = moveId;
            movedata.Code = GetTimeStamp();
            movedata.MoveTime = DateTime.Now;
            movedata.Type = "StorMove";
            movedata.StorId = locadata.StorId;
            movedata.MoveNum = Convert.ToDouble(dnum);
            movedata.Status = 0;
            movedata.CreateTime = DateTime.Now;
            movedata.CreatorId = _operator.UserId;
            movedata.Deleted = false;


            //添加移库主表信息
            await Db.InsertAsync<TD_Move>(movedata);
            //添加移库明细
            await Db.InsertAsync<TD_MoveDetail>(MoveDetaillist);
            //添加台账数据
            await Db.InsertAsync<IT_RecordBook>(iT_RecordBooks);
            //库存日志增加移库
            await Db.InsertAsync<PB_StockLog>(StockLog);
            //添加库存明细
            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);
            //添加库存汇总
            await Db.InsertAsync<IT_LocalMaterial>(LocalMaterial);

            //修改库存表包的货位信息
            await ExecuteSqlAsync(sqlMain);

        }

        #endregion

        #region 私有成员

        #endregion
    }
}